当目录存在时,htaccess重定向无法重定向

时间:2016-04-26 05:31:40

标签: php apache .htaccess redirect mod-rewrite

为了制作友好的URL,以下是应用的htaccess代码:

RewriteEngine On

RewriteCond %{THE_REQUEST} /.+?\.php[\s?] [NC]
RewriteRule ^ - [F]

RewriteRule    ^([^/\.]+)$    index.php?id1=$1    [NC,L,QSA]  
RewriteRule    ^([^/\.]+)/([^/\.]+)$    index.php?id1=$1&id2=$2    [NC,L,QSA] 

现在适用于:

  1. mydomain.com/pagesmydomain.com/index.php?id1=pages

  2. mydomain.com/pages/xyzmydomain.com/index.php?id1=pages&id2=xyz

  3. 此外,当我在网址中手动输入mydomain.com/index.php?id1=pages&id2=xyz时,它会重定向到mydomain.com

    现在,当我输入另一个像mydomain.com/templates这样的模板是一个存在的目录时,它会重定向到mydomain.com/templates/?id1=templates

    我尝试添加这些行,但徒劳无功:

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
    RewriteRule ^(.+?)/?$ /$1.php [L]
    

    我的目录结构:

    www/
        .htaccess
        index.php  <--- main router
        templates/
                img/
                css/
                ...
                ...
        other_directories/
        ...
        ...
    

    index.php应该收到id1和id2。

    如何使用htaccess避免这种情况(当存在具有该名称的目录时)?

    注意: 此问题已被问及here。但是再次发布,因为它没有获得相当多的观点也没有回答这个问题!

3 个答案:

答案 0 :(得分:1)

您应该使用重定向规则在目录前强制使用尾部斜杠:

RewriteEngine On

RewriteCond %{THE_REQUEST} /.+?\.php[\s?] [NC]
RewriteRule ^ - [F]

# add a trailing slash to directories
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*?[^/])$ %{REQUEST_URI}/ [L,R=302]

RewriteRule ^([^/.]+)/?$ index.php?id1=$1 [L,QSA]

RewriteRule ^([^/.]+)/([^/.]+)/?$ index.php?id1=$1&id2=$2 [L,QSA] 

答案 1 :(得分:0)

注意:从不测试

RewriteEngine On

# If the director's are static     
# Redirect exclude for templates, also can add the aonther directory's
RewriteRule ^(templates|another_directory)($|/) - [L]    

# Redirect General
RewriteRule ^([a-zA-Z0-9-/]+)/([a-zA-Z0-9-/]+)$ index.php?id1=$1&id2=$2 [L]
RewriteRule ^([a-zA-Z0-9-/]+)/([a-zA-Z0-9-/]+)/ index.php?id1=$1&id2=$2 [L]
RewriteRule ^([a-zA-Z0-9-/]+)/$ index.php?id1=$1 [L]

<强>结果

mydomain.com/pages/ = mydomain.com/index.php?id1=1

mydomain.com/pages/xyz = mydomain.com/index.php?id1=pages&id2=xyz

它不会重定向到mydomain.com/templates/和mydomain.com/another_directory /

答案 2 :(得分:0)

如果/ templates是现有目录,则可以使用RewriteCond

将其排除
RewriteCond %{REQUEST_URI} !^/templates [NC]
RewriteRule    ^([^/\.]+)$    index.php?id1=$1    [NC,L,QSA]

或者您可以在其他规则之前使用以下规则来更改uri:

RewriteRule ^templates - [L]