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
1 |
sudo a2enmod rewrite |
Step 2. Now open your site configuration file and update code inside the directory tag.
1 2 3 4 5 6 7 8 9 10 |
<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
1 2 3 4 |
RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] |
Redirect www website to non-www in Apache server
1 2 3 4 |
RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L] |
That’s it hope this code helps you.