1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| user nginx; worker_processes auto;
error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid;
events { worker_connections 1024; # 并发连接数限制 use epoll; # Linux 下推荐使用 epoll 模型 multi_accept on; # 尽可能多地接受连接 }
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;
sendfile on; tcp_nopush on; tcp_nodelay on;
keepalive_timeout 65; types_hash_max_size 2048;
server_tokens off; # 不暴露 Nginx 版本号,提升安全性
gzip on; # 启用压缩,提升传输效率 gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
include /etc/nginx/conf.d/*.conf;
## ## HTTPS Server ## server { listen 443 ssl http2; # 开启 HTTP/2 server_name nginx.baby;
ssl_certificate /etc/nginx/ssl/nginx.baby.pem; ssl_certificate_key /etc/nginx/ssl/nginx.baby.key;
ssl_session_timeout 10m; ssl_session_cache shared:SSL:10m; ssl_protocols TLSv1.2 TLSv1.3; # 禁用旧协议 ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on;
add_header Strict-Transport-Security "max-age=31536000" always; # HSTS 安全强化
location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ =404; } }
## ## HTTP Redirect to HTTPS ## server { listen 80; server_name nginx.baby; return 301 https://$host$request_uri; } }
|
- 性能优化
worker_processes auto:自动根据 CPU 核心数设置工作进程数。
worker_connections 1024:每个 worker 最大连接数。
sendfile on:启用零拷贝,提高文件传输效率。
tcp_nopush, tcp_nodelay:优化 TCP 性能。
keepalive_timeout 65:合理设置连接保持时间。
- 安全优化
server_tokens off:隐藏 Nginx 版本。
ssl_protocols、ssl_ciphers:只启用安全的 TLS 协议和加密算法。
HSTS:强制客户端走 HTTPS,防止降级攻击。
可选开启 HTTP Basic 认证。
- 压缩优化
gzip on:开启 gzip 压缩,减少带宽占用。
gzip_types:指定压缩的内容类型。
HTTP/2
加快 HTTPS 加载速度,提升用户体验。
蹭墙缓存
1 2 3 4
| location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 30d; access_log off; }
|