How to redirecting non-www to www with .htaccess

I’ve come across using this multiple times, so thought of putting it in a post for reference in the future.

This is the best way I could find that can be used on any website.

#For redirecting to www

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

  • The above can be used on any website as it doesn’t include the actual domain name. Change to https for if your site supports.

#For redirecting to non-www (or bare domain)

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

  • Change my-domain to actual domain name. Change to https for if your site supports.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s