【问题标题】:Using mod_rewrite to hide .php from the end of URLs使用 mod_rewrite 从 URL 的末尾隐藏 .php
【发布时间】:2011-03-06 09:44:25
【问题描述】:

我有一个网站,所有页面都是 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)或所有请求(并让我陷入循环)。

【问题讨论】:

标签: php apache mod-rewrite seo


【解决方案1】:
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} 是)。

【讨论】:

    【解决方案2】:

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

    RewriteCond %{REQUEST_URI} .*\.php
    

    到:

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

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

    【讨论】:

    • 看我的回答。您的解决方案只是略有不同(仅适用于 GET 请求)。
    【解决方案3】:

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

    【讨论】:

    • 我认为这也行,但似乎行不通。此外,对于条件RewriteCond %{IS_SUBREQ} =false,我得到[localhost/sid#1fd6de0][rid#5aa2e20/initial/redir#1] (4) [perdir U:/htdocs/] RewriteCond: input='false' pattern='=false' => matched
    【解决方案4】:

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

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

    【讨论】:

    • 我试过了,没有任何区别。为了避免歧义,我已将其添加到问题的版本中。
    【解决方案5】:

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

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

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

    【讨论】:

    • 我已经用我的 .htaccess 文件完整地重写了这个问题。添加 .php 的规则出现在删除它并重定向的规则之后。 AFAICS,RewriteCond 出了点问题
    猜你喜欢
    • 1970-01-01
    • 2012-05-11
    • 2020-10-31
    • 2011-09-08
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多