仅在文件不存在时重定向

问题描述 投票:1回答:2

我有一个用例,文件夹中可以有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]
apache .htaccess
2个回答
2
投票

-f需要完整的文件系统路径,%{REQUEST_FILENAME}表示当前请求的完整路径的文件名。

你的规则必须这样写:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(wp-content/uploads/[^/]+/test)\.html?$ $1.php [NC,L]

1
投票

我认为在你的情况下,你想要优先考虑.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,否则按原样运行。

© www.soinside.com 2019 - 2024. All rights reserved.