【问题标题】:Redirect all traffic to index.php using mod_rewrite使用 mod_rewrite 将所有流量重定向到 index.php
【发布时间】:2012-01-25 15:03:44
【问题描述】:

我正在尝试构建一个 url 缩短器,并且我希望能够在域之后立即获取任何字符并将它们作为变量 url 传递。比如

会变成

这是我现在对 mod_rewrite 的要求,但我不断收到 400 Bad Request:

RewriteEngine on  
RewriteCond %{REQUEST_FILENAME} !-f  
RewriteCond %{REQUEST_FILENAME} !-d  
RewriteRule ^(.*) index.php?url=$1 [L,QSA]  

【问题讨论】:

  • 查看error.log 了解实际错误原因。否则设置RewriteLog
  • Simple Mod Rewrite的可能重复
  • -1:需要更多调试;请参阅@mario 的评论。
  • 首先添加 RewriteBase 指令是个好主意。二、服务器允许mod_rewrite?

标签: php mod-rewrite apache


【解决方案1】:

在框架文件夹中创建一个包含以下内容的 .htaccess 文件

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule ^$ public/ [L]
    RewriteRule (.*) public/$1 [L]
</IfModule>

然后在 framework/public 文件夹中创建一个包含内容的 .htaccess 文件

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?url=$1 [L]
</IfModule>

通过添加上面的 .htaccess 文件,我们可以使网站上的 URL 更加用户友好。 例如,如果我们写一个类似的 URL

http://google.com/asdf

将转换为

http://google.com?url=asdf

出于测试目的,我们在公共文件夹中创建一个 php index.php 文件,内容如下

<?php
    echo $_GET['url'];
?>

如果在浏览器中使用上面的 URL 运行,结果是 404 not found,很可能是在步骤 1 中没有启用 mod_rewrite。如果结果是 500 Internal Server Error,可能是写入 .htaccess 时出错

【讨论】:

    【解决方案2】:

    要将所有请求重写为/index.php,您可以使用:

    RewriteEngine on
    
    
    RewriteCond %{REQUEST_URI} !^/index.php$
    RewriteRule ^(.+)$ /index.php?url=$1 [NC,L]
    

    RewriteCondition RewriteCond %{REQUEST_URI} !^/index.php$ 很重要,因为它排除了我们正在重写的重写目标并防止无限循环错误。

    【讨论】:

      【解决方案3】:

      ByTheWay 不要忘记在 ubuntu 上的 apache 中启用 mod 重写

      sudo a2enmod rewrite 
      

      然后重启apache2

      sudo /etc/init.d/apache2 restart
      

      编辑:这是一个帮助我的老问题,但我在一侧测试我的 apache2.conf 文件和另一侧的 .htaccess 文件时浪费了几个小时,但仍然没有光。

      【讨论】:

        【解决方案4】:

        检查 Apache 模块并确保启用了重写模块。我有一个类似的问题,通过启用重写模块解决了。

        【讨论】:

        • 回答一个超老问题已经回答过有什么用?
        • 实际上这在搜索了 2 小时后解决了我的问题,我不是 PHP 程序员,但我在我的网站上使用过几次。
        【解决方案5】:

        尝试不使用RewriteCond

        【讨论】:

        • 这两行RewriteCond 是为了确保真正存在的文件和文件夹不会被重写。例如,http://example.com/images/logo.png 如果该图像存在,则不会被重写。
        • @Rocket 很高兴知道以供将来参考。我只是在处理我收到的信息。
        【解决方案6】:

        尝试将^(.*) 替换为^(.*)$

        RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]
        

        编辑:尝试将index.php 替换为/index.php

        RewriteRule ^(.*)$ /index.php?url=$1 [L,QSA]
        

        【讨论】:

        • 我试了一下,但仍然收到 400 Bad Request。现在翻阅日志,但我似乎找不到任何值得的东西
        • @bswinnerton:尝试在index.php 之前添加/。检查我更新的答案。
        • 好的,所以我不再收到错误了,但是当我输入 /asdf =/ 时它不会重定向到 url=asdf
        • @bswinnerton:“当我输入 /asdf”是什么意思?您要加载的 URL 是什么?
        • 例如,如果我输入 google.com/asdf,它只会返回 google.com 而不是 google.com/?url=asdf
        猜你喜欢
        • 2021-11-16
        • 1970-01-01
        • 2014-07-08
        • 2013-08-26
        • 2018-04-03
        • 1970-01-01
        • 2015-04-10
        • 2011-12-30
        相关资源
        最近更新 更多