httpd Redirect / Rewrite .com to .org

David W asked:

I am trying to redirect a www.example.com to www.example.org. I cannot figure out what I’m doing wrong.

I have ensured that mod_rewrite is enabled in httpd.conf with:

LoadModule rewrite_module modules/mod_rewrite.so

I further verify this by running:
httpd -M and getting rewrite_module (shared) included in the results.

Later in the same httpd.conf file is the VirtualHost directive where I am trying to perform the rewrite:

<VirtualHost *:80>
    Options +FollowSymlinks
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^example.com [NC]
    RewriteRule ^(.*)$ http://www.example.org/$1 [R=301,NC,L]

    ServerAdmin admin@my-domain.com
    DocumentRoot /var/www/html
    ServerName example.org
    ServerAlias www.example.org *.example.org
        <Directory "/var/www/html">
                Options Includes FollowSymLinks
                AllowOverride All
                Order allow,deny
                Allow from all
        </Directory>
    ErrorLog /var/www/logs/error_log
    CustomLog /var/www/logs/access_log common
</VirtualHost>

As we can see, we are following SymLinks in the directory (which I believe is a requirement), AND we allow All Overrides (which meets another requirement). But obviously I’m still doing something wrong.

Can you spot it?

My answer:


Two issues here:

  1. You have only rewritten example.com to www.example.org, not any other hostname. I think you’ll want something like:

    RewriteCond %{HTTP_HOST} !www.example.org [NC]
    
  2. You also need to put the rewrite rule into a <VirtualHost> which answers for the hostnames you want to redirect, that is, it contains the ServerName and/or ServerAlias entries for the hostnames to be redirected.


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.