【问题标题】:htaccess redirect fails to redirect when directory exists目录存在时htaccess重定向无法重定向
【发布时间】:2016-08-19 18:07:08
【问题描述】:

为了制作友好的 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

另外,当我在 URL 中手动输入 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。但是又发帖了,既没有获得足够的浏览量,也没有回答问题!

【问题讨论】:

  • 您的目录(如模板)是静态的还是动态的?
  • 目录是静态的吧?它位于文件系统位置
  • 您可以添加不想重定向的目录; RewriteRule ^(templates|another_directory)($|/) - [L]
  • 谢谢.. 但是我可以看到主目录的索引页仍然没有被指向.. 它的指向模板目录(我启用了目录列表,所以它显示了目录内容)

标签: php apache .htaccess redirect mod-rewrite


【解决方案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] 

【讨论】:

  • 我想我没有任何更改.. 仍然重定向到模板目录
  • 是的,我每次都这样做,它显示mydomain.com/templates/,但在模板目录中执行索引页面
  • 完美!!感谢您的救援!
【解决方案2】:

注意:从未测试过

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/

【讨论】:

  • 这是列出模板的内容...! - 这不是我想要的
  • 我已经用目录结构更新了问题
【解决方案3】:

如果 /templates 是一个存在的目录,你可以使用 RewriteCond 排除它

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

或者您可以在其他规则之前使用以下规则来不变地传递 uri:

RewriteRule ^templates - [L]  

【讨论】:

  • 我已经用目录结构更新了问题
猜你喜欢
  • 2016-08-20
  • 1970-01-01
  • 2012-04-23
  • 1970-01-01
  • 2013-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多