首页 > 解决方案 > .htaccess 中的重定向冲突

问题描述

我们希望将博客文件夹重定向到新闻文件夹。例如:任何访问...

下面是我的 HTACCESS 代码。

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.co.uk [NC]
RewriteRule ^(.*)$ https://example.co.uk/$1 [L,R=301]
</IfModule>

# BEGIN WordPress
# The directives (lines) between `BEGIN WordPress` and `END WordPress` are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.


<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/news-blog-speaker/?$ [NC]
RewriteRule ^/blog/?$ /news/$1 [R=301,L]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

标签: wordpress.htaccessredirect

解决方案


RewriteCond %{REQUEST_URI} !^/news-blog-speaker/?$ [NC]
RewriteRule ^/blog/?$ /news/$1 [R=301,L]

上述指令存在一些问题:

  • .htaccessRewriteRule 模式匹配的 URL-path中不以斜杠开头。所以,应该是^blog,不是^/blog
  • 您只是尝试匹配/blog/blog/。但是您需要重定向/blog/<blog-title>- 如您的问题描述中所述。
  • 由于您没有捕获RewriteRule 模式中的任何内容,因此$1反向引用始终为空。您需要<blog-title>从请求的 URL 中捕获,但如上所述,您没有尝试这样做。
  • 前面RewriteCond检查请求的条件(指令)不是/news-blog-speaker完全多余的,因为您已经在检查请求是否为/blog. 不可能两者兼而有之。
  • 记下 WordPress评论。您不应该在# BEGIN/END WordPress注释标记之间手动编辑代码。

在该部分之前尝试以下操作# BEGIN WordPress

# Redirect "/blog/<blog-title>" to "/news/<blog-title>"
RewriteRule ^blog/([^/]+)/?$ /news/$1 [R=302,L]

# Redirect "/news-blog-presenters" to "/blog"
RewriteRule ^news-blog-presenters/?$ /blog [R=302,L]

通过匹配非空<blog-title>而不是简单的/blog/. 根据您声明的要求,这似乎是您所需要的。

我假设/blog它不是物理目录,否则对/blog(无尾随斜杠)的请求将触发重定向到/blog/(通过 mod_dir)。

首先使用 302(临时)重定向进行测试,并且仅在您确认重定向按预期工作后更改为 301(永久)(如果需要)。

在测试之前,您可能需要清除浏览器缓存。


推荐阅读