Nginx 常用配置全解析
一、Nginx 基础配置
全局块(main):影响 Nginx 整体运行的配置(如进程数、日志设置);
events 块:配置网络连接相关参数(如并发连接数);
http 块:定义 HTTP 服务器的核心行为(如虚拟主机、反向代理规则)。
全局配置示例
# 全局块user nginx; # 运行 Nginx 的用户(建议使用专用用户,避免 root)worker_processes auto; # 工作进程数,auto 会自动匹配 CPU 核心数(推荐)error_log /var/log/nginx/error.log warn; # 错误日志路径及级别(debug/info/notice/warn/error/crit)pid /var/run/nginx.pid; # 进程 PID 文件位置# events 块events {worker_connections 1024; # 每个 worker 进程的最大连接数(需结合系统 ulimit 调整)use epoll; # 事件驱动模型(Linux 推荐 epoll,性能最优)multi_accept on; # 允许一个 worker 同时接受多个新连接}# http 块(可包含多个 server 块,即虚拟主机)http {include /etc/nginx/mime.types; # 引入 MIME 类型映射文件default_type application/octet-stream; # 默认 MIME 类型# 其他基础配置(如日志格式、连接超时等)sendfile on; # 启用零拷贝 sendfile 机制,加速文件传输tcp_nopush on; # 配合 sendfile 使用,减少网络包数量tcp_nodelay on; # 禁用 Nagle 算法,降低延迟(适合实时通信)keepalive_timeout 65; # 长连接超时时间(秒)}worker_processes 设为 auto 可充分利用多核 CPU,避免资源浪费;
worker_connections 与 worker_processes 的乘积为理论最大并发数(需预留系统资源);
epoll 模型在高并发场景下性能远超 select/poll,是 Linux 系统的首选。
二、静态文件服务配置
1. 基础静态美国美国服务器配置
http {server {listen 80; # 监听端口(默认 80)server_name example.com www.example.com; # 绑定域名(多个用空格分隔)root /var/www/example.com; # 静态文件根目录# 首页设置location / {index index.html index.htm; # 默认首页文件,按顺序匹配try_files $uri $uri/ /index.html; # 处理单页应用路由(如 Vue/React)}# 静态资源缓存优化location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {expires 30d; # 客户端缓存 30 天(减少重复请求)add_header Cache-Control "public, max-age=2592000"; # 缓存策略access_log off; # 关闭静态资源访问日志,节省磁盘 I/O}# 禁止访问隐藏文件(如 .git、.env)location ~ /\. {deny all;access_log off;log_not_found off;}}}root:指定静态文件存放的根目录,结合 location 路径拼接完整文件路径;
expires:设置浏览器缓存时间,30d 表示 30 天,静态资源建议设置较长缓存;
try_files:用于单页应用路由跳转,当请求文件不存在时,返回 index.html 由前端框架处理。
三、反向代理配置
1. 基础反向代理配置
server {listen 80;server_name api.example.com; # 代理域名location / {proxy_pass http://127.0.0.1:8080; # 后端服务地址(IP:端口或域名)proxy_set_header Host $host; # 传递原始请求的 Host 头(后端需依赖 Host 时必设)proxy_set_header X-Real-IP $remote_addr; # 传递客户端真实 IPproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 记录代理链 IPproxy_set_header X-Forwarded-Proto $scheme; # 传递协议(http/https)# 超时设置(避免后端无响应导致连接挂起)proxy_connect_timeout 30s; # 连接后端超时proxy_send_timeout 60s; # 发送请求超时proxy_read_timeout 60s; # 读取响应超时}# 单独代理 API 路径(如 /api 转发至专门的 API 服务)location /api {proxy_pass http://127.0.0.1:8081;# 移除 /api 前缀后转发(如 /api/user → http://127.0.0.1:8081/user)rewrite ^/api(.*)$ $1 break;}}proxy_pass:后端服务器地址,末尾是否带 / 影响路径拼接(如 http://xxx:8080/ 会移除 location 路径);
proxy_set_header:设置请求头,确保后端能获取客户端真实 IP 和原始请求信息;
rewrite:用于路径重写,适合将特定前缀的请求转发至不同服务。
2. 负载均衡配置
http {# 定义后端服务器组upstream backend_servers {server 192.168.1.100:8080 weight=3; # 权重 3(处理 3/5 的请求)server 192.168.1.101:8080; # 默认权重 1server 192.168.1.102:8080 backup; # 备用服务器(主服务器故障时启用)server 192.168.1.103:8080 down; # 标记为不可用}server {listen 80;server_name app.example.com;location / {proxy_pass http://backend_servers; # 代理到服务器组proxy_next_upstream error timeout http_500 http_502 http_503 http_504; # 故障转移条件proxy_connect_timeout 10s;proxy_read_timeout 30s;}}}权重(weight):权重越高,分配的请求越多(适合服务器性能不均的场景);
IP 哈希(ip_hash):根据客户端 IP 分配固定服务器(解决会话保持问题);
upstream backend_servers {ip_hash; # 启用 IP 哈希策略server 192.168.1.100:8080;server 192.168.1.101:8080;}最少连接(least_conn):优先分配请求到连接数最少的服务器(动态调整负载)。
四、HTTPS 安全配置
1. 基础 HTTPS 配置
server {listen 443 ssl; # 监听 443 端口并启用 SSLserver_name example.com;# SSL 证书路径(推荐使用 Let's Encrypt 免费证书)ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;# 加密协议与算法(禁用不安全的 SSLv2/SSLv3/TLSv1.0/TLSv1.1)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;ssl_prefer_server_ciphers on; # 优先使用服务器定义的加密套件# SSL 会话缓存(减少握手开销)ssl_session_cache shared:SSL:10m; # 共享缓存,10MB 约可存储 40000 个会话ssl_session_timeout 1d; # 会话超时时间# HSTS 配置(强制客户端使用 HTTPS)add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;# 静态资源与反向代理配置(同前文)location / {root /var/www/html;index index.html;}}# HTTP 自动跳转 HTTPSserver {listen 80;server_name example.com;return 301 https://$host$request_uri; # 永久重定向到 HTTPS}证书推荐使用 Let's Encrypt(免费、自动续期),通过 certbot 工具快速部署;
启用 HSTS(Strict-Transport-Security)可防止中间人攻击,强制浏览器使用 HTTPS;
定期更新 Nginx 和 OpenSSL 版本,修复安全漏洞。
五、缓存优化配置
1. 代理缓存配置
http {# 定义缓存存储路径及参数proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api_cache:10m inactive=60m max_size=10g;# levels:缓存目录层级(1:2 表示两级目录,如 /var/cache/nginx/a/b123...)# keys_zone:缓存共享内存区(名称:大小),用于存储缓存键和元数据# inactive:60 分钟未访问的缓存自动清理# max_size:缓存最大磁盘占用(超过后 LRU 算法淘汰旧缓存)server {listen 80;server_name cache.example.com;location /api {proxy_pass http://backend_api;proxy_cache api_cache; # 启用缓存(关联 keys_zone)proxy_cache_key "$scheme$host$request_uri$is_args$args"; # 缓存键(确保唯一性)proxy_cache_valid 200 304 10m; # 200/304 响应缓存 10 分钟proxy_cache_valid 404 1m; # 404 响应缓存 1 分钟proxy_cache_valid any 10s; # 其他状态码缓存 10 秒# 缓存控制(客户端请求头带 no-cache 时不使用缓存)proxy_cache_bypass $http_pragma $http_cache_control;add_header X-Cache-Status $upstream_cache_status; # 响应头标记缓存状态(HIT/MISS)}}}HIT:命中缓存;
MISS:未命中缓存(请求后端);
EXPIRED:缓存过期(请求后端并更新缓存);
BYPASS:跳过缓存(如客户端指定 no-cache)。
六、日志与访问控制
1. 访问日志配置
http {# 定义日志格式(main 为格式名称)log_format main '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for" ''rt=$request_time ut=$upstream_response_time';# 字段说明:# $remote_addr:客户端 IP# $request:请求方法 + URL + 协议# $status:响应状态码# $request_time:总请求耗时(秒)# $upstream_response_time:后端响应耗时(秒)access_log /var/log/nginx/access.log main; # 启用访问日志error_log /var/log/nginx/error.log warn; # 错误日志}2. IP 访问限制
location /admin {# 仅允许特定 IP 访问后台allow 192.168.1.100; # 允许单个 IPallow 192.168.2.0/24; # 允许网段deny all; # 拒绝其他所有 IP}3. 请求限流(防止恶意攻击)
http {# 定义限流规则(req_limit 为规则名称)limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;# $binary_remote_addr:客户端 IP 二进制表示(节省内存)# zone=req_limit:10m:共享内存区(10MB 约可存储 16 万 IP)# rate=10r/s:限制速率为每秒 10 个请求server {location /api {# 应用限流规则limit_req zone=req_limit burst=20 nodelay;# burst=20:允许突发 20 个请求(超过部分排队)# nodelay:突发请求不延迟处理(立即响应,适合实时接口)proxy_pass http://backend;}}}



