Search code examples
mod-rewriteapache2.2

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


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 (!)


Solution

  • 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.