大网数据广告活动
网站运营与故障问答

301 redirects for /blog to blog subdomain not working

· 52CE 我爱测

I just created a new subdomain for my blog so blog.example.com - it used to be www.example.com/blog so I am now trying to write 301 redirects from all my old /blog posts to the new blog.example.com URLs. I have placed the followi…

问题原文

原帖链接 · jenna · CC BY-SA 3.0

I just created a new subdomain for my blog so blog.example.com - it used to be www.example.com/blog so I am now trying to write 301 redirects from all my old /blog posts to the new blog.example.com URLs. I have placed the following code in my htaccess:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^blog/(.*)$ http://blog.example.com/$1 [L,R=301]

However, do I put it after the # END Wordpress in the htaccess or am I missing something? Where in the htaccess file do I put this code or is it even the correct code?

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

OR Do I need to write out

Redirect 301 /blog/example-post http://blog.example.com/example-post

Any help would be appreciated, thanks!

已采纳解答

原帖链接 · MrWhite · CC BY-SA 3.0

...do I put it after the # END Wordpress in the htaccess or am I missing something?

No. Any external redirect should come before the # BEGIN WordPress code block. ie. Before WP internally rewrites the request.

If you placed it after the WP code block it will simply be ignored, since WP will have already routed the request.

Otherwise your mod_rewrite redirect looks OK, assuming your old /blog/ URL always has a trailing slash (to the "blog root"), the blog subdomain points to the same place on the filesystem as your main domain and you have already canonicalised the domain (ie. it can only be accessed via the www subdomain).

 Redirect 301 /blog ....

You should avoid mixing RewriteRule (ie. mod_rewrite) and Redirect (ie. mod_alias) directives. Since these two directives belong to different modules they execute at different times during the request and you can end up with confusing conflicts if you are not careful. So, since you are already using mod_rewrite (WordPress directives) then you should stick to using mod_rewrite for any redirects.

It wouldn't matter were you placed the Redirect in your config file - it would still execute after the mod_rewrite directives.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2016-10-22)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。