Redirect Virtual Host domain from WWW to non WWW or vice versa – SSL problems

Configuration & code

Redirect Virtual Host domain from WWW to non WWW or vice versa – SSL problems

mod_rewrite – URLs link magic

mod_rewrite is well known Apache module used to manipulate URL’s and is compiled into the base Apache HTTP Server. In example down below we will be working on CentOS 6/7 which manage Virtual Hosts for multiple websites.

In few easy steps you can achieve redirection such as:

  • non-SSL to SSL (http to https)
  • non-www to www
  • www to non-www

Let’s begin!

How to configure the Apache mod_rewrite module (if not configured already)

  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”> (or for default domain ex: <Directory “/var/www/html/myDomainFolder”>)

How to permanently redirect users to access the site WITH or WITHOUT the ‘www.’ prefix

Start with locating your Virtual Host configuration file for domain, in my case it’s located at: /etc/httpd/sites-available/myDomain.conf

Screenshot shows code placement & working redirection from www to non-www and forcing https for security.

Open desired VH to place code typed below at the end of section <VirtualHost *:80> (or depending of configuration ex. <VirtualHost myDomain:80>):

<IfModule mod_rewrite.c>
  # Enable mod_rewrite
  RewriteEngine on

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

  # To force redirection to 'non WWW'
  RewriteCond %{HTTP_HOST} ^www\.$uri\.$tld$ [NC]
  RewriteRule ^(.*)$ http://$domain/$1 [L,R=301]
</IfModule>

Choose either WITH or WITHOUT the ‘www.’ prefix. Do not include both or you will end up with redirection loop.

Replace http:// with https:// if you want to use SSL for certain Virtual Host using the https protocol.
SSL users can also use force SSL usage directive after Rewriting Rules:

 <Location />
 SSLRequireSSL
 </Location>

Alternative method

Create/Open a .htaccess file in the document root folder of your website and add the following text replacing variables with appropriate values where necessary.

Ex. destination: /var/www/html/myDomainFolder

Additional notes

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.
I’m 
pretty sure that “If” statement is optional at all whenever you have enabled mod_rewrite.

Note: This directive created in the apache configuration file, can’t be move easily, so consider to use .htaccess file if you preffer.

See the mod_rewrite documentation (link is external) for more information.

Restart the Apache daemon to check results

service httpd restart
, , , , , ,

Related Posts

No results found

You must be logged in to post a comment.
Menu