How to Redirect www to non-www in Apache with .htaccess

Sometimes you may need to redirect www URLs to non-www URLs for your website for SEO benefits. Here’s how to redirect www to non-www in Apache htaccess. You can use these steps to ensure that there is only one version (non-www) of your website available online.

How to Redirect www to non-www in Apache htaccess

Here are the steps to redirect www to non-www in Apache htaccess file. Please ensure that you have enabled mod_rewrite in your Apache web server configuration. Only then your htaccess configuration will be applied by Apache server.

If you have enabled htaccess using mod_rewrite, you can skip to step 4.

1. Enable mod_rewrite

Open terminal and run the following command to enable mod_rewrite on Ubuntu/Debian systems. It is already enabled in CentOS/Redhat systems.

$ sudo a2enmod rewrite

If mod_rewrite is already enabled, you will see an alert message.

Restart Apache web server

$ sudo systemctl restart apache2

Bonus Read : How to Redirect URL to Another URL

2. Enable .htaccess in Apache Server

By default, Apache does not allow the use of .htaccess file. So open the default Apache server configuration file

$ sudo vi /etc/apache2/sites-available/000-default.conf

Add the following lines just before </VirtualHost> line.

<Directory /var/www/html>
   Options Indexes FollowSymLinks MultiViews
   AllowOverride All
   Require all granted
</Directory>

Restart Apache web server

$ sudo systemctl restart apache2

3. Create .htaccess file

Open terminal and create .htaccess file

$ sudo vi /var/www/html/.htaccess

Make sure to add the following line at the top of your .htaccess file

RewriteEngine on

4. Redirect www to non-www in Apache htaccess

Let’s say you want to redirect all URLs from www.example.com to example.com

Add the following lines in your htaccess file.

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