HTTP安全头配置

必备安全响应头

响应头防护优先级
Content-Security-PolicyXSS, 数据注入
Strict-Transport-SecurityHTTP降级、中间人攻击
X-Frame-Options点击劫持
X-Content-Type-OptionsMIME类型嗅探
Referrer-PolicyReferrer信息泄露
Permissions-Policy浏览器功能滥用
Cross-Origin-Opener-PolicySpectre, XS-Leaks

Nginx配置示例

add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(self)" always;
add_header Cross-Origin-Opener-Policy "same-origin" always;

# Content Security Policy (customize for your site)
add_header Content-Security-Policy "
  default-src 'self';
  script-src 'self' 'nonce-RANDOM' https://cdn.trusted.com;
  style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
  font-src 'self' https://fonts.gstatic.com;
  img-src 'self' data: https:;
  connect-src 'self' https://api.example.com;
  frame-ancestors 'none';
  base-uri 'self';
  form-action 'self';
" always;

CSP指令参考

指令控制常用值
default-src所有资源回退'self'
script-srcJavaScript'self' 'nonce-xxx'
style-srcCSS'self' 'unsafe-inline'
img-src图片'self' data: https:
connect-srcfetch/XHR/WebSocket'self' https://api.com
frame-ancestors谁可嵌入'none' or 'self'