我怎么能在我的htaccess中有这个:
/page.php => redirects to /page
/page => shows the page.php
/index => redirects to root
以及如何从所有URL中删除尾部斜杠,特别是根目录?
虽然,我对Apache配置不够熟悉,但我可以找到这些代码:
# To remove .php extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$$1.php [NC,L]
# To remove trailing slashes
RewriteRule ^(.*)/$/$1 [L,R=301]
# To redirect /index to root (not sure if it works correctly)
RewriteCond %{THE_REQUEST} ^.*/index
RewriteRule ^(.*)index.php$/$1 [R=301,L]
你能帮我解决一下这个场景,并用一个小代码来解决它吗?
谢谢
根据答案,我可以使用我的.htaccess文件中的以下代码解决问题:
# To remove .php extension
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\ (.*)\.php [NC]
RewriteRule ^ %1 [R=301,L]
# To remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$$1 [R=301,L]
# To check whether the file exists then set it back internally
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^.*$$0.php [L]
# To redirect /index to root
RewriteCond %{THE_REQUEST} ^.*/index
RewriteRule ^(.*)index.php$/$1 [R=301,L]
现在,我遇到了一个新问题,那就是当我使用尾部斜杠浏览文件时,它会将我重定向到其他地方并发生404(找不到页面)响应,如下所示:
http://domain.tld/page/ => http://domain.tld/page/home/user/public_html/domain.tld/page
此外,如果我将第二部分移动到最后甚至完全删除它,服务器会向我发送500(内部服务器错误)响应.
最后通过一些研究,我可以使用这个建议找到以前问题的解决方案:
https://stackoverflow.com/a/27264788/5420319
所以,我改变了其中一个代码:
# To remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$$1 [R=301,L]
对此:
# To remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /(.*)/$
RewriteRule ^ /%1 [R=301,L]
而且无论是否有效,我都将这部分移到了顶部.
最佳答案 将page.php重定向到/ page:
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\ /page\.php [NC]
RewriteRule ^ /page [R=301,L]
现在,在内部设置为page.php:
RewriteRule ^page$/page.php [NC,L]
删除尾部斜杠:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$$1 [R=301,L]
现在,检查/ some / page / foo的文件是否存在/some/page/foo.php:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^.*$$0.php [L]