如何在htaccess中删除目录上的斜杠?

时间:2016-06-04 14:28:25

标签: apache .htaccess mod-rewrite query-string

我有一个像这样设置的文件夹:

/blog/blog-post-name/post-content.txt

我的网站根目录中有另一个页面,其中包含post-content.txt,方法是在查询字符串中包含目录名称,如下所示:

/blog.php?path=blog-post-name

但是,为了让网址看起来更好,我希望用户能够通过以下链接访问帖子:

/博客/博客-后名称

我创建了一个如下所示的htaccess文件,用查询字符串在内部重定向到url。

RewriteEngine on
# if not a file
RewriteCond %{REQUEST_FILENAME} !-f
# and if the directory exists
RewriteCond %{REQUEST_FILENAME} -d
# take old folder and append to query string
RewriteRule ^blog/(.*)$ blog/post.php?path=$1 [NC,L]

问题是,因为这实际上是一个目录,所以它想要添加一个尾部斜杠。我可以使用DirectorySlash off,但我已经阅读了security concerns。有没有更安全的方法将目录重定向到文件,或者这只是一个坏主意?

1 个答案:

答案 0 :(得分:1)

要删除目录使用的尾部斜杠:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]

如果您对上述内容有疑问,可以尝试以下方法:

RewriteEngine on
RewriteRule (.+)/$ /example/$1 [L,R=301]

第三种选择:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]