In this post I am going to explain to you how we can redirect a non-www website to www website or www to non-www on Apache server in simple steps.

Step 1. Before we start to hope you already enable mod_rewrite. If not then run below command

sudo a2enmod rewrite

Step 2. Now open your site configuration file and update code inside the directory tag.

<VirtualHost *:80>
     ....   
        <Directory /var/www/html/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
        </Directory>
     ...
</VirtualHost>

Step 3. Now go to your project directory and create a .htaccess file in it.

Redirect non-www website to www in Apache server

To do redirection copy paste below code in .htaccess file

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

Redirect www website to non-www in Apache server

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

That’s it hope this code helps you.