public function isHttps() { if ( ! empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') { return TRUE; } else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') { return TRUE; } else if ( ! empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') { return TRUE; } return FALSE; }
如果系统是通过nginx proxy_pass访问过来的,那么以上判断要想生效,得需要前端的nginx把用户的访问协议传给后端应用
配置 Nginx 的转发选项:
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
配置X-Forwarded-Proto 就是为了正确地识别实际用户发出的协议是 http 还是 https
X-Forwarded-For 是为了获得实际用户的 IP。
# nginx 部分配置参考 server { server_name www.zhangblog.com; listen 443; index index.jsp; ssl on; ssl_certificate /mnt/releaseCert/serverbundle.crt; ssl_certificate_key /mnt/releaseCert/serverbundle.key; if ($request_uri ~* ".html$"){ rewrite ^/(.*)$ http://$host/$1 redirect; } location / { proxy_pass http://10.171.27.25:9002; # 内网IP proxy_set_header HOST $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } server{ server_name www.zhangblog.com; listen 80; index index.jsp; if ($request_uri ~* "/pmcs/$"){ rewrite ^/(.*)$ https://$host/$1 redirect; } if ($request_uri ~* "/pmcs/login.jsp$"){ rewrite ^/(.*)$ https://$host/$1 redirect; } location / { proxy_pass http://10.171.27.25:9002; proxy_set_header HOST $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }