I\'ve got just one page that I want to force to be accessed as an HTTPS page (PHP on Apache). How do I do this without making the whole directory require HTTPS? Or, if you s
I have been through many solutions with checking the status of $_SERVER[HTTPS] but seems like it is not reliable because sometimes it does not set or set to on, off, etc. causing the script to internal loop redirect.
Here is the most reliable solution if your server supports $_SERVER[SCRIPT_URI]
if (stripos(substr($_SERVER[SCRIPT_URI], 0, 5), "https") === false) {
header("location:https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
echo "<meta http-equiv='refresh' content='0; url=https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]'>";
exit;
}
Please note that depending on your installation, your server might not support $_SERVER[SCRIPT_URI] but if it does, this is the better script to use.
You can check here: Why do some PHP installations have $_SERVER['SCRIPT_URI'] and others not
// Force HTTPS for security
if($_SERVER["HTTPS"] != "on") {
$pageURL = "Location: https://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
}
header($pageURL);
}
<?php
// Require https
if ($_SERVER['HTTPS'] != "on") {
$url = "https://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
header("Location: $url");
exit;
}
?>
That easy.
Don't mix HTTP and HTTPS on the same page. If you have a form page that is served up via HTTP, I'm going to be nervous about submitting data -- I can't see if the submit goes over HTTPS or HTTP without doing a View Source and hunting for it.
Serving up the form over HTTPS along with the submit link isn't that heavy a change for the advantage.
If you use Apache or something like LiteSpeed, which supports .htaccess files, you can do the following. If you don't already have a .htaccess file, you should create a new .htaccess file in your root directory (usually where your index.php is located). Now add these lines as the first rewrite rules in your .htaccess:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
You only need the instruction "RewriteEngine On" once in your .htaccess for all rewrite rules, so if you already have it, just copy the second and third line.
I hope this helps.
Use $_SERVER['HTTPS']
to tell if it is SSL, and redirect to the right place if not.
And remember, the page that displays the form does not need to be fed via HTTPS, it's the post back URL that needs it most.
Edit: yes, as is pointed out below, it's best to have the entire process in HTTPS. It's much more reassuring - I was pointing out that the post is the most critical part. Also, you need to take care that any cookies are set to be secure, so they will only be sent via SSL. The mod_rewrite solution is also very nifty, I've used it to secure a lot of applications on my own website.