我有一个用例,文件夹中可以有HTML或PHP文件,但用户只能访问HTML文件。我只是在缺少HTML文件时才寻找htaccess重定向。经过一些研究,我尝试下面的代码,无论文件是否存在,总是重定向到php文件。因此,如果有一个文件test.html,则无需重定向到test.php。
RewriteEngine on
RewriteCond ^wp-content/uploads/(.*)/test.html !-f
RewriteRule ^wp-content/uploads/(.*)/test.html?$ wp-content/uploads/$1/test.php [NC,L]
-f
需要完整的文件系统路径,%{REQUEST_FILENAME}
表示当前请求的完整路径的文件名。
你的规则必须这样写:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(wp-content/uploads/[^/]+/test)\.html?$ $1.php [NC,L]
我认为在你的情况下,你想要优先考虑.html
文件,如果遗漏,.php
并强制用户甚至他们请求.php
访问.html
除非找不到,所以请尝试以下代码:
RewriteEngine On
RewriteCond %{THE_REQUEST} \s/+(.*?/)?(?:index)?(.*?)\.php[\s?/] [NC]
RewriteRule ^ /%1%2 [R,L,NE]
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ /$1.html [L]
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ /$1.php [L]
上面的代码将传递所有.html
并检查请求而不使用.html
扩展,并删除.php
请求并检查是否存在具有相同名称的.html
,否则按原样运行。