代码之家  ›  专栏  ›  技术社区  ›  rjmunro

使用mod_rewrite从URL结尾隐藏.php

  •  6
  • rjmunro  · 技术社区  · 15 年前

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

    5 回复  |  直到 13 年前
        1
  •  7
  •   Steve Clay    13 年前
    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
  •  0
  •   Pete    15 年前

    将以.php结尾的页面重定向到不带.php的页面

    然后,您的第一个规则将所有不以.php结尾的页都倒回到以.php结尾的页名。

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

        3
  •  0
  •   gnarf    15 年前

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

    RewriteRule ^(.*)$ $1.php [L] #  serve the PHP file
    
        4
  •  0
  •   Your Common Sense    15 年前

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

        5
  •  0
  •   Community CDub    8 年前

    多亏了一个指针 this question 通过@thedeadmedic,我可以通过更改以下内容找到解决自己问题的方法:

    RewriteCond %{REQUEST_URI} .*\.php
    

    到:

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

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