Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

http

php

https

ssl

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.

like image 256
Jubair Avatar asked Mar 31 '11 05:03

Jubair


People also ask

Should I redirect from HTTP to HTTPS?

Without SSL, your website will show insecure to the visitors. Therefore, using an SSL-encrypted connection for safety, accessibility or PCI compliance reasons is necessary. It becomes very important to redirect from HTTP to HTTPS.

How do I transition from HTTP to HTTPS?

On the surface, changing from http to https is pretty straightforward: Purchase an SSL certificate, Install your SSL certificate on your website's hosting account, Make sure that any website links are changed from http to https so they are not broken after you flip the https switch, and.

What does it mean to redirect http to HTTPS?

Although HTTP and HTTPs seem similar enough, it's important to know the difference between the two. Here's how it all boils down: HTTPS is secure, while HTTP is not. The websites that have made the move to redirect HTTP to HTTPS appear with a padlock on the browser bar before the URL.


1 Answers

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]
like image 106
alex Avatar answered Oct 19 '22 05:10

alex