apache - 如何在 htaccess 中删除目录上的斜线?

标签 apache .htaccess mod-rewrite query-string

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

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

我网站的根目录中有另一个页面,它将通过在查询字符串中包含目录名称来包含 post-content.txt,如下所示:

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

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

/博客/博客帖子名

我创建了一个如下所示的 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 .是否有更安全的方法将目录重定向到文件,或者这通常只是一个坏主意?

最佳答案

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

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]

关于apache - 如何在 htaccess 中删除目录上的斜线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37631362/

相关文章:

regex - 如何为多个目录创建 htaccess 重定向

apache - Wordpress 选项 FollowSymLinks 错误

.htaccess - 重写 css/js 路径

.htaccess - Apache RewriteRules-什么时候不使用[L]标志?

php - 从 Laravel 5 URL 中删除 public 和 index.php 的最佳方法

apache - Perl 库无法在 WampServer 上运行

apache - WSDL2Java。 Apache CXF。 ArrayOf {Type}列出<Type>

php - URL 重写规则在 php 中不起作用

objective-c - 使用 objective-c 的 Web 应用程序编程?

apache - Nutch 不会抓取表单中的所有链接