apache - 如何删除php扩展并将扩展重定向到无扩展表单

标签 apache .htaccess mod-rewrite url-redirection

我怎么能在我的 htaccess 中有这个:

/page.php => redirects to /page
/page => shows the page.php
/index => redirects to root

以及如何从所有 URL 中删除尾部斜杠,特别是根 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]

而且不管效果如何,我也把这部分移到了顶部。

最佳答案

根据答案和我自己的研究,这将是最终答案:

# To remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /(.*)/$
RewriteRule ^ /%1 [R=301,L]

# To remove .php extension
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\ (.*)\.php [NC]
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]

关于apache - 如何删除php扩展并将扩展重定向到无扩展表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33021181/

相关文章:

php - PHP 代码中的错误

apache - 在同一个 Apache 中将 https 重定向到 https

php - Symfony 忽略 web/中的目录

apache - htaccess 通过查询字符串阻止请求

flash - 深层链接 URL 问题

linux - apache 重写的 URL 包含完整的 Linux 路径

Apache .htaccess 与 httpd - 这真的很重要吗?

apache - 模组重写 : apply to all js and css files except

.htaccess - HTTPS 与 HTTP 缓存 Javascript 文件?

apache - mod_rewrite 和超链接