使用mod_rewrite将所有流量重定向到index.php

时间:2011-12-21 20:30:24

标签: php mod-rewrite apache

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

会变成

这就是我现在对mod_rewrite所拥有的,但我一直收到400错误请求:

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

6 个答案:

答案 0 :(得分:11)

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

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

修改:尝试将index.php替换为/index.php

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

答案 1 :(得分:1)

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

sudo a2enmod rewrite 

然后重启apache2

sudo /etc/init.d/apache2 restart

编辑:这是一个老问题,帮助了我,但是我在一边测试了我的apache2.conf文件而在另一边测试了.htaccess文件但仍然没有亮光。

答案 2 :(得分:1)

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

RewriteEngine on


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

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

答案 3 :(得分:0)

不使用RewriteCond即可试用。

答案 4 :(得分:0)

在framework文件夹中创建一个.htaccess文件,内容如下

<form class="xForm">
  <label for='newName'>file</label>
  <input type='text' class='newName' placeholder='new name' />
  <input type='button' name='change' class='btnSelected' value='Modify' />
</form>
<form class="xForm">
  <label for='newName'>file</label>
  <input type='text' class='newName' placeholder='new name' />
  <input type='button' name='change' class='btnSelected' value='Modify' />
</form>

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

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

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

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

将转换为

http://google.com/asdf

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

http://google.com?url=asdf

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

答案 5 :(得分:-1)

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

相关问题