redirect www to non-www in apache

How to Redirect www to non-www in Apache 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

Bonus Read : How to Redirect All Pages to New Domain

 

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

Bonus Read : Redirect Site to Another Domain in Apache

 

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]

In the above lines the RewriteCond directive checks HTTP_HOST value of every request. If it begins with www.example.com, then RewriteRule directive permanently redirects it to example.com along with original URL string. If you want to redirect only temporarily, use R=302 above, instead of R=301.

Bonus Read : How to Redirect Domain Without Changing URL

 

5. Restart Apache Server

Restart Apache web server

$ sudo systemctl restart apache2

 

Now your Apache web server will automatically redirect www URLs to non-www URLs.

Ubiq makes it easy to visualize data in minutes, and monitor in real-time dashboards. Try it Today!

mm

About Ubiq

Ubiq is a powerful dashboard & reporting platform for small & medium businesses. Build dashboards, charts & reports for your business in minutes. Get insights from data quickly. Try it for free today!