2

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>
0

1 Answer 1

2

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.

4
  • Indeed, I was not paying attention. Using Redirect is the most straightforward thing to do in this situation. Thanks for your help and also for the alternative using RewriteRule, I still have a lot to learn in that area.
    – wouter205
    Commented Nov 15, 2021 at 15:29
  • @wouter205 You're welcome. I've just realised I didn't add any explanation regarding the Redirect directive - I've updated my answer.
    – MrWhite
    Commented Nov 15, 2021 at 15:33
  • Perfect! I only used Redirect for HTTPS redirection so I forgot that anything that comes after the match is copied as well. Good reminder :-)
    – wouter205
    Commented Nov 15, 2021 at 15:42
  • Yes, this is often overlooked.
    – MrWhite
    Commented Nov 15, 2021 at 15:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.