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

Adding a subdirectory to a URL using .htaccess

· 52CE 我爱测

I am trying to achieve the following: This URL: www.example.com/wis/9-3/1998/0.general Redirected to this URL: www.example.com/9440/wis/9-3/1998/0.general So I'm trying to add this subdirectory to the target URL: /9400/ Also, /0.…

问题原文

原帖链接 · jcmaad · CC BY-SA 4.0

I am trying to achieve the following:

This URL: www.example.com/wis/9-3/1998/0.general

Redirected to this URL: www.example.com/9440/wis/9-3/1998/0.general

So I'm trying to add this subdirectory to the target URL: /9400/

Also, /0.general changes, so that needs to be obtained from the original URL.

This is what I currently have, but it doesn't work:

RewriteRule ^/wis/9-3/1998/(.*)$ /9400/wis/9-3/1998/$1 [L]

已采纳解答

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

RewriteRule ^/wis/9-3/1998/(.*)$ /9400/wis/9-3/1998/$1 [L]

This won't work in a directory (or .htaccess) context because of the slash prefix on the RewriteRule pattern. In .htaccess only a partial URL-path is matched, which notably does not start with a slash. So, this should be written:

RewriteRule ^wis/9-3/1998/(.*) /9400/wis/9-3/1998/$1 [L]

(The end $ is superfluous since regex is greedy by default.)

Note also that this is an internal rewrite, not an external "redirect", as you've stated in your question. (Although an internal rewrite might well be what you require?)

Note also, @dan's comment above. Generally, the regex should be as specific as possible.

You could also "simplify" the above directive to save repetition:

RewriteRule ^(wis/9-3/1998/.*) /9400/$1 [L]

UPDATE#1: Within my htaccess I have some default wordpress expressions

If this is WordPress the you can't perform this type of internal rewrite in .htaccess - because of the way WordPress routes the URLs (it looks at the requested URL, to the rewritten URL).

However, you can use an external redirect (ie. the URL changes). In which, case this should go at the top of your .htaccess file, before the WordPress front-controller:

RewriteRule ^(wis/9-3/1998/.*) /9400/$1 [R,L]

Note the addition of the R flag. (This is a temporary 302 redirect.)

UPDATE#2: is there a way to include a range where 1998 is located. Let's say from 1998 to 2005

Regex is not very good for doing "ranges", however, since you have a fairly limited range you can use alternation and include each possible value: 1998, 1999, 2000, etc.:

RewriteRule ^(wis/9-3/(?:1998|1999|2000|2001|2003|2003|2004|2005)/.*) /9400/$1 [R,L]

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

资料来源与适用范围

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

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

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