CyberPanel Community

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

qt
qtwrk #1

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 http://your-domain.com/index.html , if will redirect to http://www.your-domain.com/index.html , and then to httpS://www.your-domain.com/index.html

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

6 replies
tu
tuhinbhuiyan #2

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]

Ky
Kyzoe #3

we use the following:

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

rb
rbr #4

Not working anymore

ia
ianw5555 #5

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

Ma
Macleo #6

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!

Di
Diego #7

Not working for me, redirection stopped working.

Sign in to reply