使用mod_rewrite从URL末尾隐藏.php

使用mod_rewrite从URL末尾隐藏.php,php,apache,mod-rewrite,seo,Php,Apache,Mod Rewrite,Seo,我有一个网站,所有页面都是php脚本,所以URL都是end.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 th

我有一个网站,所有页面都是php脚本,所以URL都是end.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

但这似乎发送了一个重定向,即使URL不是以.php结尾,所以我陷入了一个无限循环。我尝试的任何其他组合似乎都不匹配任何请求(将我留在page.php)或所有请求(使我陷入循环)。

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

然后,第一条规则将所有不以.php结尾的页面重新连接到以.php结尾的页面名称


这就是为什么您有一个循环:-)

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

您可能还可以将
[L]
添加到用于添加
.php
的重写规则中,以便它停止处理其他规则:

RewriteRule ^(.*)$ $1.php [L] #  serve the PHP file
多亏了@TheDeadMedic的一个指针,我能够通过更改以下内容找到解决我自己问题的方法:

RewriteCond %{REQUEST_URI} .*\.php
致:

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

RewriteEngine On

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

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

只有
%{u-REQUEST}
在第二条规则中发生的内部重定向中没有被重写(
%{REQUEST\u-URI}

我尝试了这一点,但没有任何区别。我已将其添加到问题中的版本以避免歧义。请检查我已使用.htaccess文件完整重写了问题。添加.php的规则位于删除它并重定向的规则之后。AFAICS,这台机器出了点问题,我原以为它也会起作用,但似乎不起作用。此外,对于条件
RewriteCond%{IS_SUBREQ}=false
,我得到匹配的
[localhost/sid#1fd6de0][rid#5aa2e20/initial/redir#1](4)[perdir U:/htdocs/]RewriteCond:input='false'pattern='=false'=>请参见我的答案。您的解决方案只是略有不同(仅适用于GET请求)。
RewriteEngine On

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

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