Last updated on August 10th, 2020 at 03:05 am
Many times you may need to redirect non-www URLs to www URLs for your website, to avoid duplicate search results and for SEO benefits. Here’s how to redirect non-www to www in Apache htaccess. You can use these steps to ensure that there is only one version (www) of your website available online.
How to Redirect non-www to www in Apache htaccess
Heres’s how to redirect non-www to www in Apache htaccess file for your website. Please make sure that you have enabled mod_rewrite in your Apache web server configuration. Otherwise your htaccess configuration will not be applied by Apache server.
If you have enabled htaccess (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 www to non-www in Apache
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 URL to Another URL
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 : How to Redirect All Pages to New Domain
4. Redirect non-www to www in Apache htaccess
Let’s say you want to redirect all URLs from example.com to www.example.com
Add the following lines in your htaccess file.
RewriteCond %{HTTP_HOST} ^example.com [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
In the above lines the RewriteCond directive checks HTTP_HOST value of every request. If it begins with example.com, then RewriteRule directive permanently redirects it to www.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 Site to Another Domain
5. Restart Apache Server
Restart Apache web server
$ sudo systemctl restart apache2
Now your Apache web server will automatically redirect non-www URLs to www URLs.
Ubiq makes it easy to visualize data in minutes, and monitor in real-time dashboards. Try it Today!
Sreeram Sreenivasan is the Founder of Ubiq. He has helped many Fortune 500 companies in the areas of BI & software development.