How to Redirect Non-WWW to WWW in .htaccess

redirect non www to www htaccess

For search engine optimization, it is advisable to keep only one version of your site – non-www or www. So if you have many backlinks for the www version of your website, then you might want to redirect non-www version of your site to the www version. Luckily Apache allows you to easily redirect non-www to www using .htaccess (mod_rewrite). Here’s how to redirect non-www to www in .htaccess.


How to Redirect Non-WWW to WWW in .htaccess

Here’s how to redirect non-www to www in .htaccess. Basically, you need to open .htaccess file in a text editor, add rewrite rules given below, and restart the Apache server. Before we proceed, please ensure you have enabled mod_rewrite in Apache. Here are the steps for:

  1. Ubuntu/Debian systems
  2. CentOS and similar systems

mod_rewrite allows you to modify server settings using a simple file, .htaccess, without accessing Apache server config files. You will find it in your website’s root folder (e.g /var/www/html). If you cannot find it, just create a black file with name .htaccess.


1. Edit .htaccess file

Open .htaccess file in a text editor

$sudo nano /var/www/html/.htaccess


2. Add redirect rules

If you want to redirect non-www to www, add the following rules to .htaccess file. Replace with your domain name

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


Or you can use the following code, which will work for any domain

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


If you want to redirect non-www to www with https,

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]



3. Restart Apache Server

Restart Apache Web Server to apply changes

$ sudo systemctl restart apache2 [Ubuntu/Debian]
$ sudo systemctl restart httpd [RHEL/CentOS]


Thats’ it! Apache will automatically redirect non-www to www URLs




About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!