使用 mod_rewrite 隐藏 URL 末尾的 .php
我有一个网站,其中所有页面都是 php 脚本,因此 URL 以 .php 结尾。
我已将以下内容添加到 .htaccess 文件中,现在可以访问不带 .php 扩展名的 .php 文件:
RewriteEngine On # Turn on rewriting
RewriteCond %{REQUEST_FILENAME}.php -f # If the requested file with .php on the end exists
RewriteRule ^(.*)$ $1.php # serve the PHP file
到目前为止一切顺利。但现在我想在所有 .php 文件上添加重定向,以便我控制之外的任何旧链接都可以重定向到新版本的 URL。
我已经尝试过这个:
RewriteEngine On # Turn on rewriting
RewriteCond %{REQUEST_URI} .*\.php
RewriteRule ^(.*)\.php$ http://example.com/$1 [R=permanent,L]
RewriteCond %{REQUEST_FILENAME}.php -f # If the requested file with .php on the end exists
RewriteRule ^(.*)$ $1.php [L] # serve the PHP file
但这似乎会发送重定向,即使对于不以 .php 结尾的 URL,所以我陷入了无限循环。我尝试的任何其他组合似乎都不匹配任何请求(并将我留在 page.php)或所有请求(并使我陷入循环)。
I've got a site where all the pages are php scripts, so the URLs end .php.
I've added the following to a .htaccess file, and I can now access the .php files without the .php extension:
RewriteEngine On # Turn on rewriting
RewriteCond %{REQUEST_FILENAME}.php -f # If the requested file with .php on the end exists
RewriteRule ^(.*)$ $1.php # serve the PHP file
So far so good. But now I want to add a Redirect on all the .php files so that any old links outside of my control get redirected to the new version of the URL.
I've tried this:
RewriteEngine On # Turn on rewriting
RewriteCond %{REQUEST_URI} .*\.php
RewriteRule ^(.*)\.php$ http://example.com/$1 [R=permanent,L]
RewriteCond %{REQUEST_FILENAME}.php -f # If the requested file with .php on the end exists
RewriteRule ^(.*)$ $1.php [L] # serve the PHP file
but that seems to send a redirect even for URLs that don't end in .php, so I get stuck in an infinite loop. Any other combination I try seems to match no requests (and leave me at page.php) or all requests (and get me stuck in a loop).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只有
%{THE_REQUEST}
在第二条规则中发生的内部重定向中不会被重写(另一方面,%{REQUEST_URI}
会被重写)。Only
%{THE_REQUEST}
is not rewritten in the internal redirection that happens in the second rule (%{REQUEST_URI}
, on the other hand, is).您将以 .php 结尾的页面重定向到没有 .php 的页面
然后您的第一条规则将所有不以 .php 结尾的页面重写为以 .php 结尾的页面名称
这就是为什么您有一个循环:-)
You redirecting pages ending with .php to the page without .php
Then your first rule rewites all pages not ending with .php to the page name ending with .php
This is why you have a loop :-)
您也许还可以将
[L]
添加到 RewriteRule 中以添加.php
,以便它停止处理其他规则:You might be able to also add
[L]
to the RewriteRule for adding.php
, so that it stops processing the other Rules:将
NS
添加到最后一条规则的参数列表中Add
NS
to parameters list of that last rule感谢指向这个问题通过@TheDeadMedic,我能够通过将以下内容更改为:来找到自己问题的解决方案:
不过,
我不明白为什么我的版本没有做同样的事情。
Thanks to a pointer to this question by @TheDeadMedic, I was able to find a solution to my own problem by changing:
to:
I don't understand why my version didn't do the same thing, though.