9

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? Ideally 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.

donohoe
  • 13,867
  • 4
  • 37
  • 59
Zia
  • 2,735
  • 3
  • 30
  • 27
  • possible duplicate of [Force SSL/https using .htaccess and mod_rewrite](http://stackoverflow.com/questions/4398951/force-ssl-https-using-htaccess-and-mod-rewrite) – Gordon Mar 31 '11 at 07:01
  • possible duplicate of [Force SSL HTTPS With Zend Framework and mod_rewrite](http://stackoverflow.com/questions/1329647/force-ssl-https-with-zend-framework-and-mod-rewrite) – Gordon Mar 31 '11 at 07:02
  • @Gordon you are duplicate finding king! – alex Mar 31 '11 at 10:09
  • @alex http://chat.stackoverflow.com/transcript/11?m=453322#453322 ;) – Gordon Mar 31 '11 at 10:11
  • yea I was looking for a way to do it with PHP not .htaccess file though it seems the best way to do it IS by .htaccess – Zia Apr 10 '11 at 01:34

3 Answers3

14

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]
Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
0

redirect it before the request reach the real app server, i.e. redirect it on reverse proxy like nginx/apache.

James.Xu
  • 8,249
  • 5
  • 25
  • 36
0

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]
Ilya Saunkin
  • 18,934
  • 9
  • 36
  • 50