<?php
function isHttps(): bool
{
if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
return true;
}
return false;
}
?>
此時 `$_SERVER['HTTPS']` 可能未設定,需檢查 `X-Forwarded-Proto`:
<?php
function isHttpsProxied(): bool
{
// 直接 HTTPS
if (isHttps()) return true;
// 代理頭部(注意:需信任代理,防止偽造)
$forwardedProto = $_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '';
if ($forwardedProto === 'https') return true;
// Cloudflare
if (($_SERVER['HTTP_CF_VISITOR'] ?? '') !== '') {
$visitor = json_decode($_SERVER['HTTP_CF_VISITOR'], true);
if (($visitor['scheme'] ?? '') === 'https') return true;
}
// 前端端口判斷(非標準情況)
if (($_SERVER['SERVER_PORT'] ?? 80) == 443) return true;
return false;
}
// 強制導向 HTTPS
if (!isHttpsProxied()) {
$host = $_SERVER['HTTP_HOST'] ?? '';
$uri = $_SERVER['REQUEST_URI'] ?? '/';
header("Location: https://$host$uri", true, 301);
exit;
}
?>