删除 php 扩展名,停止访问带有 .php 扩展名的 url 并删除尾部斜杠 [英] remove php extension, stop access of url with .php extension and remove trailing slashes
问题描述
我希望我的 url 没有扩展名,所以没有 .php 扩展名,我也不希望有机会访问带有斜杠的 URL.
I want my urls to be extensionless, so no .php extension, I also want there not to be an opportunity to access the URL with a trailing slash.
如果您尝试使用 .php 访问它,以下内容将删除 php 扩展名,然后重定向到无扩展名的 url
The following removes php extension and thens redirects to the extensionless url if you try to access it with .php
我开始写一个规则来阻止你使用/和重定向访问,但它不起作用,有什么帮助吗?
I started writing a rule to stop you accessing with a / and redirect, but it does not work, any help?
#this removes php extension
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)$ $1.php [NC,L]
# stops you accessing url with.php
RewriteCond %{THE_REQUEST} ^[A-Z]+ /([^.? ]+).php
RewriteRule ^([^.]+).php(/.+)?$ /$1%{PATH_INFO} [R=301]
# stops you accessing url with / **DOESNT WORK**
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)/$ /$1 [R=301,L]
推荐答案
你在倒退:你的第一条规则不是删除 php 扩展",而是 添加到尚无它的网址(从技术上讲,任何不包含句点的网址).
You're looking at things backwards: the first rule you have doesn't "remove the php extension", it adds it to URLs that don't already have it (technically, any that don't contain a period).
我想你想要更像这样的东西:
I think you want something more like this:
RewriteEngine On
RewriteBase /
# Remove .php from any URLs that contain it, using an external 301 redirect
RewriteCond %{QUERY_STRING} !^no-redirect-loop(&|$)
RewriteRule ^(.*).php$ $1 [NS,R=301,L]
# Now add it back internally
RewriteCond %{QUERY_STRING} !^no-redirect-loop(&|$)
RewriteRule ^(.*)$ $1.php?no-redirect-loop [NS,QSA]
在调试时另一个类似的答案,我意识到我在此处发布的先前解决方案不适用于 .htaccess 文件.我已经编辑了上面的示例代码,改为使用一个相当丑陋的 kluge 来中断重定向循环.kluge 的一个副作用是所有脚本都会看到一个名为 no-redirect-loop
的额外空 URL 参数.
While debugging another similar answer, I realized that the previous solution I posted here wasn't going to work in an .htaccess file. I've edited the example code above to use a rather ugly kluge for breaking redirect loops instead. A side effect of the kluge is that all scripts will see an extra empty URL parameter named no-redirect-loop
.
这篇关于删除 php 扩展名,停止访问带有 .php 扩展名的 url 并删除尾部斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!