Nginx未实施HTTP严格传输安全(HSTS)

漏洞描述:

HTTP 严格传输安全 (HSTS) 规定,浏览器只能使用 HTTPS 访问网站。检测到您的 Web 应用程序未实施 HTTP 严格传输安全 (HSTS),因为响应中缺少严格传输安全报头。

修复方法:

HSTS(Strict-Transport-Security)是HTTP响应头,用于告诉客户端只能使用HTTPS协议与服务器进行通信,其作用是:
· 强制客户端使用https,避免http明文传输
· 防止中间人攻击(MITM)
· 提高网站的整体安全性。

示例:

server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}

server {
listen 443 ssl;
server_name example.com;

# SSL 证书和其他 SSL 配置

# 添加 HSTS 头部
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
}

配置步骤:

重定向http请求到https

首先,需要在 Nginx 配置文件中将所有 HTTP 请求重定向到 HTTPS

server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}

添加 HSTS 头部

在 HTTPS 的 server 块中,添加 Strict-Transport-Security 头部,以确保浏览器在未来的一段时间内(例如一年)仅使用 HTTPS 访问网站

server {
listen 443 ssl;
server_name example.com;

# SSL 证书和其他 SSL 配置
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
}

参数解释

max-age=31536000:HSTS 策略的有效期为31536000秒(1年);

includeSubDomains:该策略适用于所有子域名;

preload:可选参数,表示如果浏览器支持,请将该策略预加载到缓存中;

always: 参数确保即使请求返回非 2xx 状态码,HSTS 头也会被发送。

posted @ 2025-04-03 10:11  Linux小飞象  阅读(741)  评论(0)    收藏  举报