4

I have an Apache configuration setup with multiple virtual hosts as subdomains. I have just purchased a new domain name, and I want all requests to this domain name to redirect to the new one, including subdomains:

old.com > new.com
sub.old.com > sub.new.com

Is there any easy way to do this inside the httpd.conf?

1 Answer 1

5

It's been awhile since I've written a RewriteRule, but here's my crack at it:

RewriteEngine on

RewriteCond %{HTTP_HOST} (.+\.)?old\.com$ [NC]
RewriteRule (.*) http://%1new.com$1 [R]

Place this in a name-based virtualhost for old.com. Here's the thought process, so that you can have a shot at correcting it on your own if I'm a bit rusty:

RewriteCond breakdown:

  • RewriteCond matches all incoming hosts for a prefix of "one or more characters followed by a literal dot", followed by old.com. The dot is inside of the parenthesis because it will not be present unless a subdomain component was supplied.
  • Backslashes are to escape the meaning of the dots. (make them literal)
  • The ? specifies that everything contained in the parenthesis is optional. (the subdomain component)
  • The $ character anchors the regex to the end of the string, to prevent premature matching weirdness.
  • The [NC] flag forces this to be case insensitive.
  • Since the virtualhost will ensure that every string contains a matching pattern, this match by itself does nothing. The important thing is that the parenthesis will capture the subdomain component of the incoming host header for the upcoming RewriteRule.

RewriteRule breakdown:

  • Capture the entire URI of the incoming request with (.*).
  • Skipping ahead, the [R] flag specifies a redirection action.
  • The redirection URL has two substitutions:
    • The first is %1, which is the first string captured by RewriteCond. In this case it should be the domain suffix. The lack of a prefixing dot before new.com is important: there might not have been a subdomain component, in which case there should be no dot. The dot should have been captured as part of the RewriteCond regex.
    • The second is $1, which matches the first string captured by RewriteRule. This should be the URI the user was attempting to access under the subdomain.

If someone points out a solution to this that averts the use of RewriteRule, bravo to them: you should prefer that as your solution where possible. mod_rewrite is for when you lack a more elegant solution provided by dedicated configuration directives.

I should also note that this example will only do non-HTTPS redirection, and does not take into consideration whether or not the webserver is using an alternative port. You may need to tweak this further for special needs such as those, but it is a starting point.

1
  • This works perfectly. Really appreciate you breaking it down, helped me to learn a bit! Thank you so much. Jan 12, 2013 at 12:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .