Loading...

Knowledge Base

How to Redirect Non-www to www in Apache

Learn how to redirect non-www to www in Apache. Note that using a non-www domain can have disadvantages, such as the following:

  • You cannot restrict cookies to a specific subdomain or root domain. On the other hand, a www URL lets you limit cookies. Therefore minimizing the number of HTTP requests and enhancing website performance.
  • Search engines treat http://yourdomain.com and https://www.yourdomain.com as different sites, which means they are ranked separately.
  • You cannot redirect it to another server because it does not have a CNAME. So, if your server is experiencing overload, you can't redirect it to another server. Therefore, visitors will have a difficult time accessing your site.

Apache Redirect Non-www to www Using .htaccess

Follow the steps below:

  1. Ensure that your hosting provider has turned on the Apache Rewrite Module. If it is not turned on, then you will not be able to install the redirect properly.
  2. Find your website's root folder and download the .htaccess file from there. Place your file in a folder where you can edit it later on.

    Important: Make a duplicate copy and save it in another file if you need to revert to the original file later on.

  3. Open the version that you are going to edit and install using Notepad ++. Add the code below to your downloaded .htaccess file. Replace example.com with your website's domain name:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
  1. Save the file and upload it back to your website, placing it in the same folder/file from which you downloaded it.
  2. Open a browser and try visiting the non-www version (example.com) of your website. If the .htaccess file is working properly, you will be redirected to the correct version of your website.
     
    Note: We recommend that you use the site Stepforth to ensure the redirect is working. Enter your non-www website address into the HTTP Header Check. If the redirect is working correctly, you will see the example results below:
    • #1 Server Response: http://example.com
    • HTTP Status Code: HTTP/1.1 301 Moved Permanently
    • Location: http://www.example.com/
    • Redirect Target: http://www.example.com/#2 Server Response: http://www.example.com/
    • HTTP Status Code: HTTP/1.1 200 OK

If the redirect worked, then you are finished with the installation. If it didn't work, then you will need to restore the backup .htaccess file and then review the revised .htaccess, comparing it to the information above and checking for mistakes.

Review

Learn how to redirect non-www to www in Apache using the .htaccess file. Understand the redirect's benefits (for example, better search engine ranking and enhanced website performance). Remember to always have a backup before making any changes to your site.

Did you find this article helpful?

 
* Your feedback is too short

Loading...