结合Mod_rewrite规则

时间:2012-12-10 21:07:35

标签: apache .htaccess mod-rewrite

我想要重写四个网址。

  1. domain.com/index.php?id=1234 => domain.com/1234
  2. domain.com/a.php?id=1234 => domain.com/a/1234
  3. domain.com/b.php?id=4321 => domain.com/b/4321
  4. domain.com/gallery.php => domain.com/gallery
  5. 其中,index检查数据库并重定向到正确的页面(a,b,c.php等),如果找不到有效的ID,则重定向到gallery.php。

    我可以自己编写适用于每个案例的RewriteRule,但我不知道如何编写它来处理所有这些,而不会越过规则。

    这是我当前的Mod_rewrite .htaccess文件:

    RewriteEngine On
    
    RewriteCond %{REQUEST_URI} !/gallery$ #excludes case 4
    
    RewriteRule ^(.*)$ index.php?id=$1 #handles case 1
    
    RewriteRule ^(.*)/(.*)$ $1.php?id=$2 #handles cases 2 and 3
    
    RewriteCond %{REQUEST_URI} /gallery$
    RewriteRule ^/gallery$ /gallery.php [L] #handles case 4
    

    这会导致所有内容重定向到domain.com/gallery.php,并导致尝试过多重定向错误。即使我放入domain.com/a/1234,也会被重定向到domain.com/a/gallery.php

    如何更好地分离这些案例 - 如果它匹配domain.com/1234在案例1之后停止 - 如果它与domain.com/a/1234匹配则停止案例2和3 - 如果它是针对domain.com/在调用domain.com/gallery.php之后停止画廊...

    感谢所有人的帮助!

1 个答案:

答案 0 :(得分:1)

用以下代码替换您的代码:

RewriteRule ^gallery/?$ /gallery.php [L,NC] #handles case 4

RewriteRule ^([^/]+)/([^/]+)/?$ /$1.php?id=$2 [L,QSA] #handles cases 2 and 3

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ /index.php?id=$1 [L,QSA] #handles case 1