How to Redirect Non-www to www URLs Using .htaccess?

.htaccess

Redirecting non-www URLs to www is essential for consistent URL structure and better SEO. Follow these simple steps to set up the redirect.

Step 1: Access the .htaccess File

The .htaccess file is in your website’s root directory. If you can’t see it, enable hidden files in your file manager or create a new one.

Step 2: Add This Code

To redirect non-www to www, add this code to your .htaccess file:

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

If your site uses HTTPS, use this code:

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

Step 3: Save and Test

  1. Save the file.
  2. Clear your browser cache.
  3. Visit a non-www URL (e.g., example.com) to check if it redirects to www.example.com.

That’s it! You’ve successfully redirected non-www to www.