There are a couple things that need to be considered when creating an htaccess file to redirect all traffic from a domain to www.domain. Follow the instructions below to make sure you have your bases covered and traffic is redirected properly.
- mod rewrite:Make sure the rewrite_module is being loaded. You should see a line like the following in your apache configuration file (typically /etc/httpd/conf/httpd.conf).
- LoadModule rewrite_module modules/mod_rewrite.so
- Directory Options:You need to make sure you allow for the .htaccess file to have control over how the redirects work. If your document root is /var/www/html then in the httpd.conf file you need to have lines similar to the following. The most important for this example being the AllowOverride All to let the .htaccess file settings override what is in httpd.conf.
- # This should be changed to whatever you set DocumentRoot to.
- #
- #
- # Possible values for the Options directive are "None", "All",
- # or any combination of:
- # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
- #
- # Note that "MultiViews" must be named *explicitly* --- "Options All"
- # doesn't give it to you.
- #
- # The Options directive is both complicated and important. Please see
- # http://httpd.apache.org/docs/2.2/mod/core.html#options
- # for more information.
- #
- Options Indexes FollowSymLinks
- #
- # AllowOverride controls what directives may be placed in .htaccess files.
- # It can be "All", "None", or any combination of the keywords:
- # Options FileInfo AuthConfig Limit
- #
- AllowOverride All
- #
- # Controls who can get stuff from this server.
- #
- Order allow,deny
- Allow from all
- .htaccess File:You should create an .htaccess file in the root of the site you want to affect with the below contents. Make sure the permissions on the .htaccess file are 644 by issuing the command chmod 644 .htaccess. The contents below will redirect all traffic from yourdomain.com to www.yourdomain.com. In the example below you will change example.com to yourdomain.com.
- RewriteEngine On
- RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
- RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
- Test:Now open up a browser and visit http://yourdomain.com. You should be redirected to http://www.yourdomain.com.
That’s it. You are now redirecting all traffic to www.yourdomain.com.