ubuntu

Nginx在Ubuntu中的安全设置指南

小樊
32
2025-11-17 10:23:42
栏目: 智能运维

Nginx 在 Ubuntu 的安全设置指南

一 基础加固与最小暴露面

二 传输加密与 HTTPS 部署

三 访问控制与速率限制

四 运行环境与持续运维

五 可直接使用的配置片段

# /etc/nginx/nginx.conf 关键片段
http {
  include       mime.types;
  default_type  application/octet-stream;

  log_format  main  '$remote_addr - $remote_user [$time_local] '
                   '"$request" $status $body_bytes_sent '
                   '"$http_referer" "$http_user_agent" "$http_x_forwarded_for"';

  access_log  /var/log/nginx/access.log  main;
  error_log   /var/log/nginx/error.log   warn;

  server_tokens off;

  # 速率限制:每 IP 10 r/s,突发 5
  limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;

  client_max_body_size 8m;
  client_body_buffer_size 10K;
  client_header_buffer_size 1k;
  large_client_header_buffers 2 1k;

  client_body_timeout 12;
  client_header_timeout 12;
  keepalive_timeout 15;
  send_timeout 10;

  # 现代 TLS 套件与 HTTP/2
  ssl_protocols TLSv1.2 TLSv1.3;
  ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:
           ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:
           ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:
           DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
  ssl_prefer_server_ciphers on;
  ssl_session_cache shared:SSL:10m;
  ssl_session_timeout 1d;
  ssl_stapling on;
  ssl_stapling_verify on;
  resolver 8.8.8.8 8.8.4.4 valid=300s;
  resolver_timeout 5s;

  include /etc/nginx/conf.d/*.conf;
  include /etc/nginx/sites-enabled/*;
}
# /etc/nginx/sites-available/example.com 关键片段
server {
  listen 80;
  server_name example.com www.example.com;
  return 301 https://$host$request_uri;
}

server {
  listen 443 ssl http2;
  server_name example.com www.example.com;

  ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

  root /var/www/example.com/html;
  index index.html;

  # 仅允许 GET/HEAD/POST
  if ($request_method !~ ^(GET|HEAD|POST)$) {
    return 444;
  }

  # 速率限制
  limit_req zone=one burst=5 nodelay;

  # 安全错误页面
  error_page 404 500 502 503 504 /error.html;
  location = /error.html {
    internal;
    root /var/www/secure-errors;
  }

  location / {
    try_files $uri $uri/ =404;
  }

  # 可选:WebSocket Secure
  # location /wss/ {
  #   proxy_pass http://127.0.0.1:8080;
  #   proxy_http_version 1.1;
  #   proxy_set_header Upgrade $http_upgrade;
  #   proxy_set_header Connection "Upgrade";
  #   proxy_read_timeout 3600s;
  # }
}

0
看了该问题的人还看了