【问题标题】:.htaccess mod_rewrite remove .php extension, but preserve URL path.htaccess mod_rewrite 删除 .php 扩展名,但保留 URL 路径
【发布时间】:2011-06-07 20:20:07
【问题描述】:

我目前有可以正常工作的 PHP 脚本,调用方式如下: www.example.com/user.php/paul 和 www.example.com/tag.php/food

我无法让 .htaccess 正确重写。我正在努力实现这一目标: www.example.com/user/paul www.example.com/tag/food

到目前为止,我可以将 /user 重定向到 /user.php,但是 /paul 丢失了;破坏我的脚本。

我当前的 .htaccess 看起来像这样:

RewriteEngine On
RewriteCond %{THE_REQUEST} ^GET\ /([^.\ ]+\.)+php(\?[^\ ]*)?\ HTTP
RewriteRule ^(.+)\.php$ http://www.example.com/$1 [R=301,L]
RewriteRule ^([^/]+/)*index/?$ http://www.example.com/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ http://www.example.com/$1 [R=301,L]
RewriteCond $1 !^([^.]+\.)+([a-z0-9]+)$ [NC]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*[^/])$ /$1.php [L]

请帮忙。 谢谢! 保罗

【问题讨论】:

    标签: linux apache .htaccess mod-rewrite


    【解决方案1】:

    你可能应该在某处使用这样的规则:

    RewriteRule ^/([^/]*)/([^/]*)$ /$1.php/$2
    

    又是英文版。

    First comes the beginning of the path                        ^/
    The first component of the path doesn't have / symbols in it [^/]*
    We remember it                                               ()
    Then comes the slash between the components                  /
    Then the second component without the / symbols              [^/]*
    Remember it too                                              ()
    And the path ends                                            $
    

    用第一个记住的东西替换它,然后是.php/,然后是第二个记住的东西。

    您可能不想在此规则中使用[L],重定向不是必需的,用户不需要知道您的脚本确实有.php 后缀。

    希望这是正确的,我现在无法在工作的 Apache 上检查它。

    【讨论】:

      【解决方案2】:

      将此代码放入您的 .htaccess 文件中:

      Options +FollowSymlinks -MultiViews
      RewriteEngine on
      
      # external redirect to hide .php
      RewriteCond %{THE_REQUEST} ^GET\s.+\.php [NC]
      RewriteRule ^([^/]+)\.php/(.*)$ /$1/$2 [NE,R=301,L,NC]
      
      # internal redirect to add .php
      RewriteRule ^([^/]+)(?<!\.php)/(.*)$ /$1.php/$2 [L]
      

      【讨论】:

      • @Paul:也许你可以提供一些不工作的细节。顺便说一句,我在发布之前已经在我的 Linux 和 Mac 上测试了这个答案。
      • 这和以前的问题一样:/user 正确重定向到 /user.php,但是 /user/paul 给出了 404
      • 这很奇怪,因为我在我的 Win7 安装上再次测试它并且它再次工作。 user/ 文件夹内也有任何 .htaccess 吗?您可以将相关的 error.log 和 access.log 粘贴到您的问题中吗?
      • 没有实际的 /user 文件夹。 [2011 年 6 月 8 日星期三 20:15:38] [错误] [客户端 XX.XX.XX.XX] 文件不存在:/home/www.example.com/user
      • XX.XX.XX.XX - - [08/Jun/2011:20:15:37 -0700] "GET /user/paul/ HTTP/1.1" 200 1026 "-" "Mozilla /5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.77 Safari/534.24"
      猜你喜欢
      • 2013-04-20
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 2022-01-21
      • 2020-02-27
      • 1970-01-01
      • 2013-10-11
      • 2019-03-03
      相关资源
      最近更新 更多