How can I use mod_rewrite to redirect multiple hosts between domains?

180 Views Asked by At

I'm trying to redirect requests for mis-spelt domain names to the same server on the official domain.

My apache configuration looks like:

<VirtualHost *:80>
        RewriteEngine on

        # Fix domain spellings in host.<backupdomain>
        RewriteCond %{HTTP_HOST} !([^.]+).example.com [NC]
        RewriteRule ^/(.*) http://%1.example.com/$1 [NC,R,L]
</VirtualHost>

I know I'm close, because the requests to server99.wrongdomain get re-written to .example.com - and I'm expecting it to go to server99.example.com.

Why isn't the regex capture/expansion working correctly here?

P.S. Incredibly annoying that SO is blocking my original examples because they look like links (!)

2

There are 2 best solutions below

0
On BEST ANSWER

If you want to match something not followed by something else then you can use Negative lookahead.

RewriteCond %{HTTP_HOST} ^([^.]+)\.(?!example\.com) [NC]
RewriteRule ^/(.*)$ http://%1.example.com/$1 [NC,R,L]

This way, each wrong domain (with server99 for example)

  • server99.example.co.uk
  • server99.exampel.com
  • etc

will redirect to server99.example.com.

0
On

That is virtually everything you need in case you only want to redirect misspelled subdomains.

<VirtualHost *:80>
ServerName *.example.com

RedirectMatch 301 /(.*) http://www.example.com/$1

</VirtualHost>

If you want to redirect every request for which there is no uniqe VHost configuration, use the following and make sure it is the very first VHOST configuration loaded by apache

<VirtualHost _default_:80>
RedirectMatch 301 /(.*) http://www.example.com/$1
</VirtualHost>

Of course that only works if the DNS record of the FQDN points to the apache in question.