如何解决.htaccess的重定向问题,该问题删除了.php并添加了斜杠
起点:
我在.htaccess中使用以下代码。该代码删除了.php扩展名,并在末尾添加了斜杠。
Options -Indexes
Options -Multiviews
CheckSpelling off
RewriteEngine on
RewriteBase /
# forward always without www and with https
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1/ [R=301,L]
# Add a trailing slash at the end
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule . %{REQUEST_URI}/ [L,R=301]
# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]
示例:“ example.com/existing_php_file.php”变为“ example.com/existing_php_file /”
这很好用。
以下变体也按预期工作:
-
“ example.com/existing_folder/not_existing_file_or_folder”给出404消息
-
“ example.com/not_existing_file_or_folder”给出404消息
问题:
有人输入以下内容时出现重定向错误:
-
example.com/existing_php_file_without_extension/not_existing_file_or_folder
-
example.com/existing_folder/existing_php_file_without_extension/not_existing_file_or_folder
自己的分析:
我用http://www.redirect-checker.org/index.php检查了“ example.com/existing_folder/existing_php_file_without_extension/not_existing_file_or_folder”。
我似乎.htaccess中的代码添加了一个“ /”,然后是“ .php /”,然后又是一个“ /”,依此类推。
example.com/existing_folder/existing_php_file_without_extension/not_existing_file_or_folder 301永久移动example.com/existing_folder/existing_php_file_without_extension/not_existing_file_or_folder/ 301移至永久example.com/existing_folder/existing_php_file_without_extension/not_existing_file_or_folder.php/ 301永久example.com/existing_folder/existing_php_file_without_extension迁/ not_existing_file_or_folder / 301永久移动
我的重定向检查器会像上面的一样计数19个重定向。这会导致Safari和chrome(我认为其他浏览器)也会发送一个错误,指出存在许多重定向(这是事实)。
问题:
有什么想法如何修改.htacces以获取404错误而不是重定向错误?
解决方法
在某些Apache服务器上,%{REQUEST_FILENAME}
可能行为不正常。最好将此规则替换为内部投放.php
的广告:
# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*?)/?$ $1.php [L]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。