mod_rewrite重写基础

时间:2011-12-02 10:59:22

标签: php mod-rewrite apache2

我在网站上工作,我想用mod_rewrite来重写网址,比如

  

www.example.com/index.php?p=MYPAGE - > www.example.com/MYPAGE   www.example.com/index.php?p=user?u=MYUSER - > www.example.com/user/MYUSER   www.example.com/index.php?p=group?g=MYGROUP - > www.example.com/group/MYGROUP

到目前为止,我已经添加了这些规则。

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?p=$1
RewriteRule ^user/(.+)$ index.php?p=user&u=$1

但是我遇到了问题。如果我访问www.example.com/single-page一切都很好。然后,如果我访问www.example.com/user/SMTHING,我没有达到我想要的。我尝试过使用C和L标志,没有任何成功。

有什么想法吗?

谢谢

4 个答案:

答案 0 :(得分:2)

你有三个问题。首先,您的条件仅适用于它们之后的第一条规则,因此您仍将重写合法文件请求。此外,您需要使用[L] ast标志以及重新排序您的规则。把它们放在一起:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.+)$ $1                               [L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+)$ $1                               [L]

RewriteRule ^user/(.+)$ index.php?p=user&u=$1       [L]
RewriteRule ^(.+)$ index.php?p=$1

答案 1 :(得分:2)

没有答案可能看起来像我的,所以这里是:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^user/([a-zA-Z0-9-]+)$ /index.php?p=user&u=$1 [QSA,L]
RewriteRule ^group/([a-zA-Z0-9-]+)$ /index.php?p=group&g=$1 [QSA,L]
RewriteRule ^([a-zA-Z0-9-]+)$ /index.php?p=$1 [QSA,L]

我很确定它有效(或非常接近你想要的)。 请告诉我它是否有效......

顺便说一句如何更好的事情:

RewriteRule ^(user|group)/([a-zA-Z0-9-]+)$ /index.php?type=$1&val=$2 [QSA,L]

所以在你的GET中你将拥有“type = user”或“type = group”和“val = the value”。有点概括的东西。

答案 2 :(得分:0)

你试试这个吗? 它可能有用。

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^user/(.+)$ index.php?p=user&u=$1
RewriteRule ^(.+)$ index.php?p=$1

重写规则的顺序非常重要。

答案 3 :(得分:0)

试试这个,它会起作用:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([^\/]+)$ index.php?p=$1
RewriteRule ^([^\/])([^\/]+)\/([^\.]+)$ index.php?p=$1$2&$1=$3