如何在php中重写url?

时间:2012-10-19 13:15:00

标签: apache mod-rewrite

我有一些问题需要在php中重写url。

1- www.test.com/index.php?name=123到www.test.com/123

2- www.test.com/folder1/index.php?name=123到www.test.com/folder1/123/index.php

关于我在1号码上的编码,但我不知道如何用1号重写2号组合:

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

2 个答案:

答案 0 :(得分:1)

当你说“在php中重写url”时,我认为“在php中”是指应用程序的语言,而不是重写/重定向方法---因为你的示例代码包含Apache指令。 / em>的

以下规则会将test.com/folder1/index.php?name=123格式的网址更改为test.com/folder1/123格式的“漂亮”网址(我删除了'index.php'为了更加用户友好)。

  1. 重定向丑陋的查询网址,以便用户始终看到“漂亮”的网址

    RewriteCond  %{QUERY_STRING} \bname=([^&]+)
    RewriteRule  ^/?folder1/index\.php$ /folder1/%1 [R=302]
    
  2. 告诉服务器如何解释漂亮的网址

    RewriteRule  ^/?folder1/([^\/]+)(/index\.php)?$ /folder1/index.php?name=$1 [L]
    
  3. 注意: 上面的第一条规则使用302(临时)重定向,因此您的浏览器在测试和调整重定向规则时不会“记住”重定向规则。如果您关心SEO,请将[R=302]更改为[R=301],这是永久重定向。

答案 1 :(得分:0)

试试这个:

RewriteEngine on
RewriteCond  %{REQUEST_FILENAME} !-f
RewriteCond  %{REQUEST_FILENAME} !-d
RewriteRule  ^(.*)/([0-9]+)/index.php $1/index.php?name=$2 [QSA,L]
RewriteRule  ^(.*)$ index.php?usname=$1 [QSA,L]

重写规则末尾的[L]指令意味着如果规则匹配,则结束解析.htaccess。

所以你必须在规则之前放置规则^(。*)$ wich处理每个案例