2012-12-10 131 views
1

我有四个网址我想要重写。结合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

其中,索引检查数据库和重定向到正确的页面(a,b,c.php - ect),如果没有找到有效的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/gallery停止domain.com/gallery.php后调用...

感谢您的帮助所有!

回答

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 
+0

你是一个生命的救星!这很好!所以让我确保我理解这里的逻辑:RewriteCond只适用于下一个RewriteRule?所以如果我需要额外的RewriteCond来允许像css和图像和字体这样的东西,我必须在每个RewriteRule之前放置这些RewriteConds? –

+0

不客气。是的,RewriteCond只适用于下一个RewriteRule。 – anubhava