.htaccess,无法在重写条件下获取URL的第一部分

时间:2012-02-29 16:32:07

标签: .htaccess

我试图用.htaccess文件获得以下结果。

URL:                      Behavior(rewrite to):
example.com/x/            view-test.php?page=x
example.com/x/y           view-test.php?page=y&parent=x
example.com/x/y/z         view-test.php?page=z&parent=y&grandparent=z

我有以下.htaccess规则,其中还包含一些需要忽略此方案的文件夹:

RewriteCond %{REQUEST_URI}!^/(admin|images|scripts|css|fonts|view-test\.php)/ [NC]
RewriteRule ([^/]*)/([^/]*)/([^/]+)/?$ /view-test.php?grandparent=$1&parent=$2&page=$3  [L]

RewriteCond %{REQUEST_URI}!^/(admin|images|scripts|css|fonts|view-test\.php)/ [NC]
RewriteRule ([^/]*)/([^/]+)/?$ /view-test.php?&parent=$1&page=$2 [L]

RewriteCond %{REQUEST_URI}!^/(admin|images|scripts|css|fonts|view-test\.php)/ [NC]
#RewriteRule ([^/]+)$ /view-test.php?page=$1 [L]

但是,每当我取消注释最后两行时,我都会收到内部服务器错误。父/页和祖父/父/页结构工作正常。如何重新编写最后一条规则(以及前面的规则,如果是nessecary),以便为第一个模式(只是一个页面)获得所需的结果?

3 个答案:

答案 0 :(得分:0)

请改用此代码:

RewriteCond %{REQUEST_URI} ^/(admin|images|scripts|css|fonts|view-test\.php)/ [NC]
RewriteRule ^ - [L,S=3]

RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ view-test.php?grandparent=$1&parent=$2&page=$3 [L,QSA]

RewriteRule ^([^/]+)/([^/]+)/?$ view-test.php?&parent=$1&page=$2 [L,QSA]

RewriteRule ^([^/]+)/?$ view-test.php?page=$1 [L,QSA]

问题是您在上次RewriteRule条件中缺少尾部斜杠/

答案 1 :(得分:0)

# remove slash at the end to prevent redirect loop
RewriteCond %{REQUEST_URI} ^/(OIE|admin|images|scripts|css|fonts|view-test\.php) [NC]
RewriteRule ^ - [L]

RewriteRule ([^/]*)/([^/]*)/([^/]+)/?$ /OIE/view-test.php?grandparent=$1&parent=$2&page=$3  [L]

RewriteCond %{REQUEST_URI}!^/(admin|images|scripts|css|fonts|view-test\.php)/ [NC]
RewriteRule ([^/]*)/([^/]+)/?$ /OIE/view-test.php?&parent=$1&page=$2 [L]

RewriteCond %{REQUEST_URI}!^/(admin|images|scripts|css|fonts|view-test\.php)/ [NC]
RewriteRule ([^/]+)/?$ /OIE/view-test.php?page=$1 [L]

答案 2 :(得分:0)

试试这个:

    RewriteEngine On
    RewriteBase /
    RewriteRule ^([a-zA-Z0-9_-]+)$ view-test.php?page=$1

    RewriteEngine On
    RewriteBase /
    RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ view-test.php?page=$1&parent=$2

    RewriteEngine On
    RewriteBase /
    RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ view-test.php?page=$1&parent=$2&grandparent=$3