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

.htaccess and permanent redirection with a special condition

· 52CE 我爱测

I have a WordPress website hosted on Bluehost which contains the following URL pattern: http://www.example.com/2017/01/30/sample-post/ I wanted to permanent redirect it to use this: http://www.example.com/sample-post/ So I opened…

问题原文

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

I have a WordPress website hosted on Bluehost which contains the following URL pattern:

http://www.example.com/2017/01/30/sample-post/

I wanted to permanent redirect it to use this:

http://www.example.com/sample-post/

So I opened .htaccess kept in the example.com folder and changed it to the following with the help of a suggestion by w3dk.

RewriteEngine On
RewriteRule ^\d{4}/\d\d/\d\d/(.+) /$1 [R=301,L]

# 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

After I wrote this rewrite rule, everything of the URL format example.com/2017/01/30/sample-post works great. However, there are a few URLs in the website that have the format example.com/name-of-category/2008/10/20/sample-post and are throwing a 404 as the result of the above rewrite rule.

I want to permanently redirect www.example.com/name-of-category/2008/10/20/sample-post to www.example.com/name-of-category/sample-post.

What change do I need to make in my .htaccess file?

已采纳解答

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

To handle category posts of the form /name-of-category/2008/10/20/sample-post then include something like the following directive after the existing redirect.

RewriteRule ^([a-z-]+)/\d{4}/\d\d/\d\d/(.+) /$1/$2 [R=301,L]

This would redirect /name-of-category/2008/10/20/sample-post to /name-of-category/sample-post. Note that the category consists of just the lowercase a-z and the - (hyphen), as in your example.

If you needed to allow more characters in the category then changing [a-z-] to [\w-] in the above RewriteRule pattern would allow a-z, A-Z, 0-9, _ and -. But it is better to be as restrictive as possible.

So, in summary:

RewriteEngine On
RewriteRule ^\d{4}/\d\d/\d\d/(.+) /$1 [R=301,L]
RewriteRule ^([a-z-]+)/\d{4}/\d\d/\d\d/(.+) /$1/$2 [R=301,L]

:

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

资料来源与适用范围

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

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

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