Add or Remove WWW Prefix in Domain URL

Redirecting a domain to WWW is a very simple task. In this tutorial you will show you how to add or remove www on Apache (using mod_rewrite) and Nginx web servers.

For example http://mydomain.com should be redirect to http://www.mydomain.com.

Add WWW PREFIX IN DOMAIN URL

Go to your website’s home directoty:

cd /home/username/public_html

Open the .htacess file with any of your favourite editors:

nano .htaccess

Insert the following code in file.

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

Save the file.

Assign proper ownership to the file.

This will redirect all requests to the non-www version of your site to the www version using 301.

 

For Nginx users add the following code in domains server block.

server {
 server_name example.com;
 return 301 http://www.example.com$request_uri;
}

Remove WWW Prefix in Domain URL

Add the following code in your web server configuration. This will remove www prefix from site url. If some one opened site with www, this will redirect to non-www url.

Apache users add the following code in your website .htaccess file. It will required the mod_rewrite enabled on your server, without mod_rewrite it will not work.

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

Nginx users add the following code in domains server block.

server {
 server_name www.example.com;
 return 301 http://example.com$request_uri;
}