使用mod_rewrite从URL末尾隐藏.php

时间:2010-06-21 16:09:33

标签: php apache mod-rewrite seo

我有一个网站,其中所有网页都是php脚本,因此网址结束.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文件上添加一个Redirect,以便我控制之外的任何旧链接都被重定向到新版本的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结尾的网址,这似乎也会发送重定向,因此我陷入无限循环。我尝试的任何其他组合似乎都没有匹配任何请求(并留在page.php)或所有请求(并让我陷入循环)。

5 个答案:

答案 0 :(得分:7)

RewriteEngine On

RewriteCond %{THE_REQUEST} ^\w+\ /(.*)\.php(\?.*)?\ HTTP/
RewriteRule ^ http://%{HTTP_HOST}/%1 [R=301]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule .* $0.php

在第二个规则(%{THE_REQUEST}中发生的内部重定向中,不会重写%{REQUEST_URI},而另一方面,是{。}>。

答案 1 :(得分:0)

您将以.php结尾的页面重定向到没有.php的页面

然后你的第一条规则将所有不以.php结尾的页面重写为以.php结尾的页面名称

这就是你有一个循环的原因: - )

答案 2 :(得分:0)

NS添加到最后一条规则的参数列表

答案 3 :(得分:0)

您也可以将[L]添加到RewriteRule以添加.php,以便停止处理其他规则:

RewriteRule ^(.*)$ $1.php [L] #  serve the PHP file

答案 4 :(得分:0)

感谢@TheDeadMedic指向this question的指针,我通过更改找到了解决自己问题的方法:

RewriteCond %{REQUEST_URI} .*\.php

为:

RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP

我不明白为什么我的版本没有做同样的事情。