What is the best practice for automatically switching from HTTP to HTTPS

I am curious. What is the best practice for automatically switching a user from http://www.example.com to https://www.example.com

i.e. from http to https? Ideally, I would like to make it so that no matter what url (and any possible data)

There are a few things people talk about, like checking $_SERVER ["SERVER_PROTOCOL"] or $_SERVER['SERVER_PORT'] or $_SERVER['HTTPS'] , but I would like to know what is the best practice.

+8
php ssl
source share
3 answers

Php

If you want to get http to https to do this ...

 if ( ! isset($_SERVER['HTTPS'])) { header('Location: https://' . $_SERVER["SERVER_NAME"] . $_SERVER['REQUEST_URI']); } 

However, if your site has its own port, you also need to add $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'] also not set in IIS if you use it.

Apache.htaccess / httpd.conf

 RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://www.example.com/$1 [R,L] 
+13
source

redirect it before the request reaches the real application server, i.e. redirect it to a reverse proxy, for example nginx / apache.

0
source

Put these lines in your .htaccess file in the root directory of your site

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

also, if you have only some directory that you want to protect (for example, the directory where the script login is located), then put the .htaccess file in this directory containing these lines

 RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteCond %{REQUEST_URI} /path/to/directory RewriteRule ^(.*)$ https://www.yousite.com/path/to/directory/$1 [R,L] 
0
source

All Articles