Published January 17, 2018 by

Redirect non www to www in Apache Web Server

Here I show how to redirect a website from www to non-www and non-www to www, using the Apache server configuration.

1. non www to www

For example, Here I set redirect rule for

serverkaka.com
To
www.serverkaka.com

To do this add following code into an apache virtual host file. (<VirtualHost *:80>)

RewriteEngine on
rewritecond %{http_host} ^serverkaka.com [nc]
rewriterule ^(.*)$ http://www.serverkaka.com/$1 [r=301,nc]

Replace highlight text with your domain name


After saving file insert below command for enabling 'RewriteEngine'

# sudo a2enmod rewrite

Restart Apache Server


# sudo service apache2 restart                          ## For Ubuntu/Debian
# sudo systemctl restart httpd                          ## For CentOS/RedHat


2. www to non www

For example, Here I set redirect rule for

www.serverkaka.com
To
serverkaka.com

To do this add following code into an apache virtual host file. (<VirtualHost *:80>)


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

After saving file insert below command for enabling 'RewriteEngine'

# sudo a2enmod rewrite

Restart Apache Server

# sudo service apache2 restart                          ## For Ubuntu/Debian
# sudo systemctl restart httpd                          ## For CentOS/RedHat