<?php
$isHttps = isset($_SERVER['HTTPS'])
&& $_SERVER['HTTPS'] !== ''
&& strtolower((string) $_SERVER['HTTPS']) !== 'off';
if ($isHttps) {
echo 'This request is using HTTPS.';
}
?>
If your site is behind a reverse proxy, do not blindly trust X-Forwarded-Proto. Only use proxy headers when requests come through a proxy you control.
header() must run before HTML or other output. Build redirects from a configured host name rather than copying an untrusted Host header directly.
<?php
$isHttps = isset($_SERVER['HTTPS'])
&& $_SERVER['HTTPS'] !== ''
&& strtolower((string) $_SERVER['HTTPS']) !== 'off';
if (!$isHttps) {
$requestUri = $_SERVER['REQUEST_URI'] ?? '/';
header('Location: https://www.example.com' . $requestUri, true, 301);
exit;
}
?>
.htaccess redirectOn Apache with mod_rewrite, a typical site-wide redirect is:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]
After enabling HTTPS, update assets and external resources that still load over http://. Browsers may block insecure images, scripts, stylesheets or frames on an HTTPS page.
https://www.example.com/images/logo.jpg
https://schema.org
If absolute HTTP URLs are stored in your own database, review them before doing a bulk replacement and take a backup first.
UPDATE table_name
SET column1 = REPLACE(column1, 'http://www.example.com', 'https://www.example.com')
WHERE column1 LIKE 'http://www.example.com%';
<?php
echo htmlspecialchars((string) ($_SERVER['HTTPS'] ?? 'not set'), ENT_QUOTES, 'UTF-8');
?>
On a direct connection, port 443 can be an additional signal. Reverse proxies can make this value different from the browser-facing port.
<?php
$isHttps = (($_SERVER['SERVER_PORT'] ?? '') === '443');
?>
This older pattern is retained for comparison. Prefer a normal HTTP redirect for HTTPS migration.
<?php
header('Refresh: 5; url=https://www.example.com/');
?>
Legacy tutorials often matched the host explicitly. The simpler HTTPS condition shown above is usually easier to maintain.
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]Older examples sometimes used the non-standard Refresh response header to redirect after a delay. For ordinary HTTP-to-HTTPS migration, an immediate permanent redirect is clearer and more reliable.
← Header Redirect Conditional Redirection →
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.