How to redirect all traffic to one domain URL via mod_rewrite?

Normally when a website is hosted, both the domain and the prefix www with it load the same website. This can sometimes cause problem as web pages can be accessed using two URLs (e.g. example.com and www.example.com).

Using mod_rewrite rules you can redirect all traffic to one domain. This is also beneficial for SEO (Search Engine Optimization) purpose to avoid duplicate URLs and pages in search engine index. Search engines are becoming smart, however they still may not like duplicate pages.

To be on the safe side and to show only one URL of your website, you can use following format of mod_rewrite rules under Apache web server in .htaccess file which is placed in your web root (typically in public_html).

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

This will redirect all traffic to one URL for all pages on your web site and there will be no duplicate URLs because of www. If you do not want to use www and instead prefer to use only example.com, you can use this instead:

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

If you have other mod_rewrite rules, placing one of the rules-set above at the top will process it first and in the next pass it will by-pass them as the URL will not match again.