萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 判斷 HTTPS 連線的正確姿勢:支援反向代理與負載均衡

基本判斷

<?php
function isHttps(): bool
{
    if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
        return true;
    }
    return false;
}
?>

反向代理/負載均衡環境(Nginx、Cloudflare、ALB)

此時 `$_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;
}
?>

安全配置建議

  • Nginx 必須設置:`proxy_set_header X-Forwarded-Proto $scheme;`
  • PHP 信任代理 IP 範圍:`Request::setTrustedProxies(['10.0.0.0/8', '172.16.0.0/12'])` (Symfony/Laravel)
  • 啟用 HSTS:`header("Strict-Transport-Security: max-age=31536000; includeSubDomains; preload");`
copyright © 萬盛學電腦網 all rights reserved