【问题标题】:Redirect URL with trailing slash to no trailing slash URL将带有斜杠的 URL 重定向到没有斜杠的 URL
【发布时间】:2021-09-29 17:33:34
【问题描述】:

我有一个特定页面,只有在 URL 带有斜杠 (/blog/) 时才能查看该页面。如果不是,它将返回错误 403。所以我想要的是我希望 /blog 重定向到 /blog/

我知道这是可能的,但我无法使用 .htaccess 来实现。我相信这已经在这里受到质疑但没有正确回答。

这是我的根 .htaccess:

Options -Indexes

ErrorDocument 404 /error/error404.html

DirectoryIndex index.html index.php

DirectorySlash Off

RewriteEngine On

RewriteCond $1 !/$
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule (.+) $1/ [L]

【问题讨论】:

  • 虽然您的 question title 似乎与您在问题中实际尝试做的事情相矛盾,那就是 append 一个斜杠,而不是去掉它。 (?)

标签: apache .htaccess


【解决方案1】:

想必这和your earlier question有关,这里很相关。 重要的是,/blog 是一个子目录,其中包含一个 WordPress 安装和一个附加的 .htaccess 文件,其中包含通常的 WordPress (mod_rewrite) 指令。这意味着父配置中的 mod_rewrite 指令被完全覆盖。

(尽管我想您之前的问题也可能否定了这个要求,因为现在可以在没有尾部斜杠的情况下访问/blog。)

所以我想要 /blog 重定向到 /blog/

为此,您可以简单地启用/blog/.htaccess 文件中的DirectorySlash。如果需要,这将允许 mod_dir 附加带有 301 重定向的尾部斜杠。例如:

# /blog/.htaccess

DirectorySlash On

# BEGIN WordPress
:

或者,有条件地禁用根 .htaccess 文件中的 DirectorySlash,以禁用除 /blog 子目录之外的所有内容。例如:

# /.htaccess

# Conditionally turn Off directory slash for everything except "/blog" 
<If "%{REQUEST_URI} !~ m#^/blog($|/)#">
    DirectorySlash Off
</If>

【讨论】: