Redirect non-www URL to www in Apache

If both www and non www domain of your website ( and serve the same website, and you want people going to to automatically be redirected to, there's a few way that you can do so with Apache

1) .htaccess

First of all, make sure mod_rewrite is installed and enabled for your Apache installation. Once it is, add a file named .htaccess in your website's root directory and add the following lines;

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

2) Virtualhost

You can also change your website's Virtualhost setting for the redirect.

<VirtualHost *:80>
    Redirect permanent /

Restart Apache for the changes to take effect

Sign up for Complete Apache HTTP Server Course and many other great courses on Udemy to learn more.

Complete Apache HTTP Server Course

Master Apache 2.4 web server and start on-demand career!

Written by Mohd Shakir Zakaria. Last updated on 2019-02-12