• Home
  • Ubuntu 18.04
    • Whats New?
    • Upgrade Ubuntu
    • Install Java
    • Install Node.js
    • Install Docker
    • Install Git
    • Install LAMP Stack
  • Tutorials
    • AWS
    • Shell Scripting
    • Docker
    • Git
    • MongoDB
  • Funny Tools
  • FeedBack
  • Submit Article
  • About Us
TecAdmin
Menu
  • Home
  • Ubuntu 18.04
    • Whats New?
    • Upgrade Ubuntu
    • Install Java
    • Install Node.js
    • Install Docker
    • Install Git
    • Install LAMP Stack
  • Tutorials
    • AWS
    • Shell Scripting
    • Docker
    • Git
    • MongoDB
  • Funny Tools
  • FeedBack
  • Submit Article
  • About Us

How to Force Redirect to www or non-www in Htaccess

Written by Rahul, Updated on July 29, 2019

For SEO purposes this is good practice to keep your website URLs either with www or without www only. In this tutorial, you will learn how to force a redirect to www or non-www URL only. 301 status code tells search engines that the page has permanently moved to a new location.

Force Redirect to WWW or Non-WWW

Login to server with admin privileges and navigate to document root of your website. Now create a .htaccess file using one of below content as per your requirements.

Force non-www to www

This will force URL as www.example.com, this will always add www in URL either you accessed it with or without www.

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

Force www to non-www

This will force URL as example.com, this will always remove www from URL, you either accessed it with or without www.

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

Enable .htaccess to Work

Before using .htaccess, make sure your .htaccess is enabled to use in Apache. To enable this add following settings under your domains VirtualHost.

<VirtualHost *:80>

    [...]
    <Directory "/home/user/public_html">
         Allowoverride all
    </Directory>
    [...]

</VirtualHost>

Enable Apache Rewrite Module

Also make sure Apache rewrite module is enabled. If not use the following command to enable module.

sudo a2enmode rewrite

Share it!
Share on Facebook
Share on Twitter
Share on LinkedIn
Share on Reddit
Share on Tumblr
Share on Whatsapp
Rahul
Rahul
Connect on Facebook Connect on Twitter

I, Rahul Kumar am the founder and chief editor of TecAdmin.net. I am a Red Hat Certified Engineer (RHCE) and working as an IT professional since 2009..

Leave a Reply Cancel reply

Popular Posts

  • How To Install Python 3.9 on Ubuntu 20.04 5
  • How to Install Python 3.9 on CentOS/RHEL 7 & Fedora 32/31 0
  • How To Install VNC Server on Ubuntu 20.04 1
  • How To Install NVM on macOS with Homebrew 0
  • How to Install .NET Core on Debian 10 0
© 2013-2020 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy