Apache rewrite multiple conditions

apache-2.2mod-rewrite

I have a website that's migrated from an old domain name (e.g. olddomain.com) to a new domain name (e.g. newdomain.com).

For SEO reasons, I need to rewrite all website traffic to the primary new domain name (e.g. www.newdomain.com). Unfortunately, I don't know how to add multiple OR type rewrite conditions. It seems that with all the conditions, sample code below, I get an AND condition.

<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        ServerName newdomain.com
        ServerAlias www.newdomain.com
        ServerAlias olddomain.com
        ServerAlias www.olddomain.com
        DocumentRoot /var/www/newdomain.com/www/
        <Directory />
                Options FollowSymLinks
                AllowOverride All
        </Directory>

        ErrorLog /var/log/apache2/error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        RewriteEngine on
        RewriteCond %{HTTP_HOST} ^olddomain.com [NC]
        RewriteCond %{HTTP_HOST} ^www.olddomain.com [NC]
        RewriteCond %{HTTP_HOST} ^newdomain.com [NC]
        RewriteRule ^/(.*)$ http://www.newdomain.com/$1 [R=301,NC]

        CustomLog /var/log/apache2/access.log combined
</VirtualHost>

Can someone give me a little assist? Any help would be greatly appreciated.

Best Answer

Despite the fact that you have already found working for you solution, I still will post this as yours is far from being optimal.

Solution #1: Replace [NC] by [NC,OR] in first 2 RewriteCond lines of the original code. By default one RewriteCond linked to another RewriteCond by logical AND. This will instruct Apache to use OR logic:

RewriteCond %{HTTP_HOST} ^olddomain.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.olddomain.com [NC,OR]
RewriteCond %{HTTP_HOST} ^newdomain.com [NC]
RewriteRule ^/(.*)$ http://www.newdomain.com/$1 [R=301,L,NC]

Solution #2: Since you have only 4 domain names in total, it will be much easier to use opposite approach - redirect from ANY domain except correct one:

RewriteCond %{HTTP_HOST} !^www.newdomain.com [NC]
RewriteRule ^/(.*)$ http://www.newdomain.com/$1 [R=301,L,NC]
Related Topic