2014-01-30 41 views
1

我已经写了下面的代码在我的htaccess index.php文件:重定向到根

RewriteRule ^(.*)/$ $1 
RewriteCond %{REQUEST_URI} !^index.php.*$ 
RewriteRule ^(.*)$ /index.php?route=$1 [END] 

它可以完美的每一条路径,除了存在目录。例如,如果我输入http://localhost/profilepic并且这样的目录实际存在,它将重定向到http://localhost/profilepic/?route=profilepic,但我希望它是隐含转换为http://localhost/index.php?route=profilepic

在此先感谢。

回答

1

这是因为mod_dir and the DirectorySlash directive。从本质上讲,如果它看到一个没有结尾斜线的URI,并且它映射到一个现有的目录,那么它将重定向请求,使其具有尾部斜线。由于mod_dir和mod_rewrite都位于URL文件处理管道的不同位置,因此mod_dir和mod_rewrite都会应用到同一个URL。这就是为什么你最终得到一个重定向和一个奇怪的URL与查询字符串。

如果你绝对必须有没有尾部斜线的目录,那么你需要打开DirectorySlash。关闭它的问题是存在信息泄露安全问题,即使您有索引文件,人们也可以查看目录的内容。这意味着你必须使用mod_rewrite来弥补mod_dir。

因此摆脱了规则:

RewriteRule ^(.*)/$ $1 

并更换这些规则:

DirectorySlash Off 

# redirect direct requests that end with a slash to remove the slash. 
RewriteCond %{THE_REQUEST} \ /+[^\?\ ]+/($|\ |\?) 
RewriteRule ^(.*)/$ /$1 [L,R] 

# internally add the trailing slash for directories 
RewriteCond %{REQUEST_FILENAME} -d 
RewriteRule ^(.*[^/])$ /$1/ [L] 
+0

谢谢Jon!这解决了这个问题;) – Javid

1

这里是另一种方式,你可以有不关闭DirectorySlash您的规则(考虑一个安全漏洞):

RewriteEngine On 

# remove trailing slash for non-directories 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{THE_REQUEST} \s(.+?)/+[?\s] 
RewriteRule ^(.+?)/$ /$1 [R=301,L] 

# routing for directories 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} -d 
RewriteRule ^(.+?)/$ /index.php?route=$1 [L] 

# routing for non directories 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.+?)/?$ /index.php?route=$1 [L] 
+0

+1这个很好的解决方案。 TNX。 L:什么意思? – Javid

+1

L是将一条规则标记为'Last',它将重写的URL重新注入mod_rewrite引擎。 – anubhava