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

How can I rewrite a URL to use a new path for Apache?

· 52CE 我爱测

How can I rewrite a URL so that following is achieved: example.com/old/index.htm is redirected to example.com/new/index.htm ? I've tried to add the following RewriteRule in my server config vhost to no avail: <Location /old> Rewr…

问题原文

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

How can I rewrite a URL so that following is achieved:

example.com/old/index.htm is redirected to example.com/new/index.htm ?

I've tried to add the following RewriteRule in my server config vhost to no avail:

<Location /old>
RewriteEngine On
RewriteRule /$1 /new/$1 [R]
</Location>

已采纳解答

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

You should never use mod_rewrite directives inside a <Location> wrapper. The docs explicitly warn against this.

However, to simply redirect "old" to "new" you don't necessarily need mod_rewrite. A simple mod_alias Redirect directive would suffice. Although a possible exception to this is if you are already using mod_rewrite for other redirects/rewrites.

For example:

Redirect 302 /old/ /new/

The Redirect directive is prefix-matching, and everything after the match is copied to the end of the target URL. So, the above will redirect /old/<anything> to /new/<anything>.

Or with mod_rewrite:

RewriteEngine On

RewriteRule ^/?old/(.*) /new/$1 [R=302,L]

R (without an explicit response code) is the same as R=302, however, it is often better to be explicit.

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

资料来源与适用范围

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

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

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