大网数据广告活动
服务器运维问答

Adding HSTS to nginx config

· 52CE 我爱测

I recently changed my nginx config to redirect all http traffic to https (and all www traffic to no-www). Would it make sense to also add add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; to my se…

问题原文

原帖链接 · Hassan Baig · CC BY-SA 3.0

I recently changed my nginx config to redirect all http traffic to https (and all www traffic to no-www).

Would it make sense to also add add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; to my server blocks as well? Or that's unneeded since I'm already redirecting all traffic? Would be great to know the pros (and cons, if any).


In case relevant, my current virtual host configuration is:

server {
    server_name example.com www.example.com;

    listen 80;

    return 301 https://example.com$request_uri;
}

server {
    server_name www.example.com;

    listen 443 ssl;

    ssl_certificate /etc/nginx/ssl/cert_chain.crt;
    ... other SSL related config ...

    return 301 https://example.com$request_uri;
}

server {
    server_name example.com;

    listen 443 ssl;
    ... other SSL related config ...

    ... remaining server configuration ...
}

已采纳解答

原帖链接 · Tim · CC BY-SA 4.0

HSTS tells the browser to always use https, rather than http. Adding that configuration may reduce the need for forwarding from http to https, so it may very slightly increase website performance and very slightly decrease server load.

For reference, here's the security headers I use on my Nginx based websites. I save this to a single file and include it from all servers that need it, including http and https servers. It allows some common resources like Google and Facebook to load.

# Security headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header Content-Security-Policy "default-src 'self' www.google-analytics.com ajax.googleapis.com www.google.com google.com gstatic.com www.gstatic.com connect.facebook.net facebook.com;";
add_header X-XSS-Protection "1; mode=block";
add_header Referrer-Policy "origin";

Clarification

You still need the http to https redirection in place.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-09-21)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0 / CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。