在 .htaccess 中将请求文件名 (%{REQUEST_FILENAME}) 更改为新路径



我正在尝试在 .htaccess 中使用与 Alias /var/www/html/core/ Alias /var/www/html/core/latest/ 相同的RewriteRule

我在/var/www/html/core 中做了这个 .htaccess

RewriteEngine On
#Check if file exist in original path (/var/www/html/core):
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
#try new path (/var/www/html/core/latest):
RewriteRule ^(.*)$ latest/$1 [NC,L]

但是,如果文件在/var/www/html/core/latest apache 中不存在,则显示内部服务器错误而不是正常的 404 错误。所以我必须在最后RewriteRule之前使用一些RewriteCond *** -f,以确保文件存在于新路径中。

问题是我无法将%{REQUEST_FILENAME}更改为latest/%{REQUEST_FILENAME}。 例如:

core/img/load.gif 必须在 core/latest/img/load.gif 中签入,而不是 latest/core/img/load.gif

是否可以以某种方式解析 .htaccess 中的%{REQUEST_FILENAME}

您可以像这样调整规则:

RewriteEngine On
RewriteBase /core/
#Check if file exist in original path (/var/www/html/core):
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
#try new path (/var/www/html/core/latest):
RewriteCond %{DOCUMENT_ROOT}/core/latest/$1 -f
RewriteRule ^((?!latest/).*)$ latest/$1 [L,NC]

RewriteCond %{DOCUMENT_ROOT}/core/latest/$1 -f确保该文件存在于/core/latest/文件夹中。

最新更新