[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 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 :)

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

Comments

  • edited August 28
    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 :)

    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]
Sign In or Register to comment.
Support CyberPanel CyberPanel Discord

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!