mod_rewrite is an Apache module used to manipulate URL's and is compiled into the base Apache HTTP Server in CentOS.  See the mod_rewrite documenation for more information.

How to configure the Apache mod_rewrite module

  1. Open the Apache configuration file located at /etc/httpd/conf/httpd.conf
  2. Change AllowOverride None to AllowOverride All inside the DocumentRoot Directory Directive, normally <Directory "/var/www/html">

Permanently redirect users to access the site WITH or WITHOUT the 'www.' prefix

  1. Create/Open a .htaccess file in the document root folder and add the following text replacing variables with appropriate values where necessary
    # mod_rewrite
    <IfModule mod_rewrite.c>
      # Enable mod_rewrite engine
      RewriteEngine on

      # WITH 'www.'
      RewriteCond %{HTTP_HOST} ^$uri\.$tld$ [NC]
      RewriteRule ^(.*)$ http://www.$domain$1 [L,R=301]

      # WITOUT 'www.'
      RewriteCond %{HTTP_HOST} ^www\.$uri\.$tld$ [NC]
      RewriteRule ^(.*)$ http://$domain/$1 [L,R=301]

    Note: Choose either WITH or WITHOUT the 'www.' prefix.  Do not include both or you will end up in a redirection loop.
    Note: If there is already an <IfModule mod_rewrite.c> directive, only copy the desired #RewriteCond and #RewriteRule lines and add them to the directive.
    Note: Replace http:// with https:// if used for a Virtual Hosts using the https protocol.
    Note: This text can also be added to the VirtualHost directive in the apache configuration file, but you can't typically move these changes to a live server, so the .htaccess file is the prefered method.
  2. Restart the Apache daemon
    service httpd restart

Open Source Software: