我们如何使用 Apache 重定向到新的 HTML 静态内容,如果未找到,则回退到基于 CMS 的旧 PHP 版本?(n



问题:

我们正在用Gatsby构建的SSG HTML版本替换一个旧的基于PHP的网站(基于Statamic v1)。

问题是:只有一部分现有页面必须替换,而成员空间以及/login/contact页面必须暂时保留。

所以我想知道我应该如何使用新版本来调整当前的.htaccess配置,首先查找在特定目录(public/)中找到的新静态内容,或者如果没有,则回退到旧的index.php?path=方法。

注意:

有了nginx这将通过try_files指令来完成 所以,这个问题在某种程度上与:
https://serverfault.com/questions/290784/what-is-apaches-equivalent-of-nginxs-try-files 但我绝对不明白balancer://app_cluster的东西..

上下文 :

以下是目录的简化视图,因为它们必须由 Apache 提供:

www/
├── index.php
├── (... more CMS files)
└── public
├── index.html
├── main.js
├── robots.txt
├── img
│   ├── intro.jpg
│   ├── logo.svg
│   └── table.png
├── about
│   └── index.html
└── staff
└── index.html

进入public/的任何内容都必须首先
提供,/public不会出现在最终网址中:

URL : /img/intro.jpg => /public/img/intro.jpg (rewritten as /img/intro.jpg)

并且每个与/index.html页面匹配的URL都必须在没有它的情况下重写:

URL : '' or '/' => /public/index.html (rewritten as '')
URL : /staff or /staff/ => /public/staff/index.html (rewritten as /staff)

每个未找到的文件都会重定向到/index.php?path=...,因为现在已准备就绪。

问题

是否只能使用 Apache 而不重新排序到两个单独的子域,并且virtual_hosts.. 来分离 2 个来源?
我想是的,鉴于阿帕奇不可思议的力量, 但是由于我现在更习惯了nginx的方式,我真的需要你的帮助!!:)

当前配置

(不要问我为什么)

# Turn on the Rewrite Engine
RewriteEngine On
# PERMANENT HTTPS REDIRECTION
RewriteCond %{REQUEST_SCHEME} =http
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# If you're running in a subfolder (like http://example.com/statamic),
# add that here. E.g. /statamic/
RewriteBase /
# Remove trailing slashes from your URL
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/(?.*)?$ $1$2 [R=301,L]
# Remove the index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

如果我理解正确,他们的关键要求是在public/中提供静态内容(如果存在),如果没有,则将请求传递给index.php

该要求相对容易处理。 规则的顺序很重要,因为它们是按顺序应用于每个传入请求的。 我们可以先对public/内容进行测试,因此如果它存在,我们将优先返回它并停止处理。 如果请求与该测试不匹配,则处理将继续进行index.php重定向。

RewriteEngine On
# If the requested file or directory exists in public/, internally redirect
# there (internally means no actual new http request, and the URL in the
# browser does not change).  Use OR flag to OR the 2 conditions, instead of
# the usual implicit AND.
RewriteCond %{DOCUMENT_ROOT}/public%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}/public%{REQUEST_URI} -d
RewriteRule ^.*$ public/%{REQUEST_URI} [L]
# If the requested file does not exist, and is not a directory, pass the
# request to index.php, appending any query string.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

请注意您提到的:

每个未找到的文件都会重定向到/index.php?path=...正如现在所做的那样。

需要明确的是,这实际上不是您现在包含的.htaccess所做的。 该规则只是将请求传递给index.php,没有path参数(尽管包括请求中已有的任何现有参数)。 您的index.php可以使用$_SERVER变量访问 - 并且肯定已经在访问 - 真实请求的路径。 但是,如果您确实希望现在按照您的描述将路径附加到查询,则必须将该规则修改为如下所示的内容:

RewriteRule ^(.*)$ index.php?path=$1 [QSA,L]

另一个旁注 - 问题和.htaccess中都有很多无关紧要的东西,我认为这混淆了这个问题,也许是为什么你在这里没有得到很好的回应。

最新更新