How to Redirect a Domain to the WWW Version Using .htaccess

On this page
  1. Before You Begin
  2. Redirect Non-WWW to WWW
  3. How It Works
  4. Redirect Non-WWW to WWW with HTTPS
  5. Testing the Redirect
  6. Common Issues
  7. Summary

If you want visitors to always access your website using the www version of your domain, you can configure a permanent redirect in the .htaccess file.

For example:

https://yourdomain.com

will automatically redirect to:

https://www.yourdomain.com

Using a consistent domain format helps avoid duplicate content issues and ensures that all traffic is directed to a single preferred address.

Before You Begin

The .htaccess file is usually located in your website’s root directory:

public_html

If the file does not exist, you can create it manually.

Important: Before editing .htaccess, create a backup copy of the file so you can easily restore the previous configuration if needed.

Redirect Non-WWW to WWW

Add the following rules to your .htaccess file:

# Redirect non-www to www

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

How It Works

  • RewriteEngine On enables URL rewriting.
  • RewriteCond %{HTTP_HOST} !^www\. [NC] checks whether the requested hostname does not start with www.
  • RewriteRule redirects the visitor to the same URL with the www prefix added.
  • R=301 creates a permanent redirect, which is recommended for SEO purposes.

Redirect Non-WWW to WWW with HTTPS

If your website uses an SSL certificate, it is recommended to redirect visitors directly to the secure HTTPS version:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

Example:

https://yourdomain.com/contact

becomes:

https://www.yourdomain.com/contact

Testing the Redirect

After saving the .htaccess file:

  1. Open your website using the non-WWW address.
  2. Verify that the browser automatically redirects to the WWW version.
  3. Test multiple pages and subpages to ensure the redirect works correctly throughout the website.

Common Issues

If the redirect does not work as expected:

  • Verify that the .htaccess file is located in the correct directory.
  • Check for conflicting redirect rules.
  • Clear your browser cache before testing again.
  • Ensure that URL rewriting is enabled on the server.

Summary

To force visitors to use the WWW version of your domain, add the following rule to the .htaccess file in your website’s root directory:

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

If your website uses SSL, replace http:// with https:// to redirect visitors directly to the secure WWW version of the site.

Didn't find an answer?

Our support team is here for you 24/7 – write to us and we will help you sort it out.