[Tutorial] How to make redirect with or without WWW and redirect to https

today someone asked me how to do redirect to domain force www and also https.

so this is little guide.

in .htaccess add folloing code

RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.your-domain.com/$1 [R,L]

please be sure replace the domain name in code.
the above code is force WWW, the following code is WITHOUT WWW

RewriteCond %{HTTP_HOST} ^www\\.your-domain\\.com
RewriteRule (.*) https://your-domain.com/$1 [R=301,L]

please be mind with . (dot) in the code , don’t remove it.

when you access , for example your-domain.com , if will redirect to your-domain.com , and then to your-domain.com

it redirect twice , which could waste some time, so I suggest we use HSTS header to force HTTPS

when a browser received HSTS , any request send to this domain in pre-set time , will automatically upgrade to HTTPS even you manually typed http:// , where this redirect is taking locally by browser , so it does’t have to communicate to server and let server indicates the redirect , could save like some time.

click here to see how to add HSTS header

original posted here by myself, and translated by myself :slight_smile:

rewrite rule from
How to Force HTTPS Using the .htaccess
and
How to Properly Redirect Your Domain With or Without www

Using second one, But its not working for redirecting HTTP and WWW to HTTPS NON-WWW.
It redirects to HTTPS WWW

Any help would be appreciate.

UPDATE:

This one worked for me :slight_smile:

Don’t forget to replace domain and .com with your own domain name and extension.

It will allow www and http to https non-www

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

we use the following:

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Not working anymore

Try this:

BEGIN Redirects

RewriteEngine On

301 redirect to www

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

301 redirect to https

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

END Redirects

Type your comment> @ianw5555 said:

Try this:

BEGIN Redirects

RewriteEngine On

301 redirect to www

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

301 redirect to https

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

END Redirects

Thx!

Not working for me, redirection stopped working.