Nginx与安全相关的几个配置
随着网络威胁的不断演变,保护网站免受潜在攻击变得尤为重要。Nginx,作为一款强大而灵活的 web 服务器和反向代理服务器,提供了一系列的安全相关参数,可以帮助加固网站安全性。在这篇文章中,我们将介绍一些基于 Nginx 的安全参数配置,以确保您的网站更加健壮和安全。
为了降低攻击者获取系统信息的可能性,我们可以通过设置 server_tokens 来隐藏服务器版本信息。在 Nginx 配置中添加如下设置:
复制
server_tokens off;1.
对于使用 HTTPS 的网站,SSL/TLS 配置至关重要。确保使用强密码和安全的协议版本。示例配置如下:
复制
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384;
ssl_prefer_server_ciphers off;1.2.3.
通过配置 X-Frame-Options 可以防止网页被嵌套在 <frame>、<iframe> 或 <object> 中,从而防止点击劫持攻击。
复制
add_header X-Frame-Options "SAMEORIGIN";1.
使用 X-XSS-Protection 头启用浏览器内置的 XSS 过滤器。
复制
add_header X-XSS-Protection "1; mode=block";1.
通过设置 X-Content-Type-Options 防止浏览器执行某些文件类型的 MIME 类型嗅探。
复制
add_header X-Content-Type-Options "nosniff";1.
为了防止恶意请求或慢速攻击,设置请求头大小和请求超时时间。
复制
client_max_body_size 10M;
client_body_timeout 12s;1.2.
这组配置禁止浏览器对响应进行缓存,确保每次请求都会向服务器验证资源的有效性。
复制
add_header Cache-Control "no-cache, no-store, must-revalidate";
add_header Expires "0";1.2.
通过设置安全的 Cookie,仅允许通过 HTTPS 传输,且不可通过 JavaScript 访问,提高对会话劫持和 XSS 攻击的防护。
复制
add_header Set-Cookie "cookie_name=value; Path=/; Secure; HttpOnly";1.
以上配置用于处理跨域请求,确保安全地允许指定域的跨域请求,并处理预检请求(OPTIONS 请求)。
复制
if ($request_method = OPTIONS) {
add_header Access-Control-Allow-Origin https://your-allowed-domain.com;
add_header Access-Control-Allow-Methods GET, POST, OPTIONS;
add_header Access-Control-Allow-Headers DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range;
add_header Access-Control-Max-Age 1728000;
add_header Content-Type text/plain; charset=utf-8;
add_header Content-Length 0;
return 204;
}
if ($request_method = POST) {
add_header Access-Control-Allow-Origin https://your-allowed-domain.com always;
add_header Access-Control-Allow-Methods GET, POST, OPTIONS always;
add_header Access-Control-Allow-Headers DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range always;
add_header Access-Control-Expose-Headers Content-Length,Content-Range always;
}
if ($request_method = GET) {
add_header Access-Control-Allow-Origin https://your-allowed-domain.com always;
add_header Access-Control-Allow-Methods GET, POST, OPTIONS always;
add_header Access-Control-Allow-Headers DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range always;
add_header Access-Control-Expose-Headers Content-Length,Content-Range always;
}1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.
以上是一些基本的 Nginx 安全配置示例,但请注意,这只是一个起点。根据您的实际需求和安全最佳实践,可以进一步调整和配置。请务必仔细查阅 Nginx 文档以获取最新的安全建议,并定期审查和更新您的安全策略,以确保网站的持续安全性。
阅读剩余
THE END