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

htaccess 301 redirect for second level sub directory

· 52CE 我爱测

I have a directory website with the following URL structure. http://mywebsite.com/information/business-name/ http://mywebsite.com/information/business-name/product-names/ http://mywebsite.com/reviews/business-name/ http://mywebsi…

问题原文

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

I have a directory website with the following URL structure.

http://mywebsite.com/information/business-name/
http://mywebsite.com/information/business-name/product-names/    
http://mywebsite.com/reviews/business-name/
http://mywebsite.com/comments/business-name/

Now, there is a change in the business name and I want to change the URLs to these -

http://mywebsite.com/information/new-business-name/
http://mywebsite.com/information/new-business-name/product-names/    
http://mywebsite.com/reviews/new-business-name/
http://mywebsite.com/comments/new-business-name/

How do I 301 redirect the old URLsto new URLs in htaccess file?

Currently, I am temporarily using the following -

RewriteRule ^information/business-name/(.*)$ /information/new-business-name/$1 [R=301,L]
RewriteRule ^reviews/business-name/(.*)$ /reviews/new-business-name/$1 [R=301,L]
RewriteRule ^comments/business-name/(.*)$ /comments/new-business-name/$1 [R=301,L]

Is there a way to rewrite it in one rule as I just need to change /business-name/ to /new-business-name/ ?

已采纳解答

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

To combine those three rules into one you can use alternation (with a vertical bar) in a capturing group and another backreference in the substitution:

For example:

RewriteRule ^(information|reviews|comments)/business-name/(.*)$ /$1/new-business-name/$2 [R=301,L]

$1 is now a backreference to either "information", "reviews" or "comments".

Depending on your situation you could make this more generic:

RewriteRule ^([^/]+)/business-name/(.*)$ /$1/new-business-name/$2 [R=301,L]

This will match any single subdirectory that precedes "/business-name/", including "information", "reviews" and "comments".

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

资料来源与适用范围

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

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

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