What is the best practice for auto switching from HTTP to HTTPS
I'm curious. What is the best practice to auto switch the user from http://www.example.com to https://www.example.com
i.e. from http to https? Idea开发者_如何学Clly I would like to make it so that no matter what the url (and any possible get data)
There are a couple things people chat about like checking $_SERVER ["SERVER_PROTOCOL"]
or $_SERVER['SERVER_PORT']
or $_SERVER['HTTPS']
but I would like to know what the best practice is.
PHP
If you want to force http
to https
, do this...
if ( ! isset($_SERVER['HTTPS'])) {
header('Location: https://' . $_SERVER["SERVER_NAME"] . $_SERVER['REQUEST_URI']);
}
However, if your site has a custom port, you'll also need to add $_SERVER['SERVER_PORT']
. $_SERVER['REQUEST_URI']
also isn't set on IIS, in case you are using it.
Apache .htaccess / httpd.conf
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
redirect it before the request reach the real app server, i.e. redirect it on reverse proxy like nginx/apache.
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 just some directory that you want to secure (e.g. the directory where the login script is found), then put an .htaccess file into that 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]
精彩评论