Nginx 使用教程(从入门到生产)
目标:一篇可以直接拿来用的 Nginx 教程。
说明:Nginx 功能非常多(含商业版增强能力),本文覆盖开源版中的核心能力与绝大多数生产常用场景,并给出可复制示例。
1. Nginx 是什么
Nginx(Engine X)是高性能 Web 服务器与反向代理服务器,也常用于:
- 静态资源服务(HTML/CSS/JS/图片)
- 反向代理(转发到后端应用)
- 负载均衡(多后端分流)
- HTTPS/TLS 终止
- 网关(限流、鉴权、跨域、缓存)
- 流量转发(TCP/UDP,需 stream 模块)
核心特点:
- 高并发、低内存占用、事件驱动
- 配置声明式、热加载(
nginx -s reload) - 模块化能力强
2. 安装与启动
2.1 Windows(快速体验)
- 下载 Nginx Windows 压缩包并解压。
- 进入目录执行:
start nginx
常用命令(Windows):
nginx -t # 检查配置语法
nginx -s reload # 重载配置
nginx -s stop # 快速停止
nginx -s quit # 优雅退出
Windows 适合开发测试;生产更推荐 Linux。
2.2 Linux(Ubuntu 示例)
sudo apt update
sudo apt install -y nginx
sudo systemctl enable nginx
sudo systemctl start nginx
sudo systemctl status nginx
3. 配置文件结构
常见文件位置(Linux):
- 主配置:
/etc/nginx/nginx.conf - 站点配置:
/etc/nginx/conf.d/*.conf或/etc/nginx/sites-enabled/* - 日志:
/var/log/nginx/access.log、/var/log/nginx/error.log
基础结构:
user nginx;
worker_processes auto;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name example.com;
root /usr/share/nginx/html;
index index.html;
}
}
作用域优先级(简化):
main(全局)eventshttp(HTTP 相关)server(虚拟主机)location(路径匹配)
4. 核心匹配规则(server 与 location)
4.1 server_name 匹配
server_name example.com www.example.com;
支持:
- 精确域名
- 泛域名:
*.example.com - 正则:
~^api\d+\.example\.com$
4.2 location 匹配优先级
location = /exact { ... } # 精确匹配,优先级最高
location ^~ /images/ { ... } # 前缀匹配且停止正则匹配
location ~ \.php$ { ... } # 正则(区分大小写)
location ~* \.(jpg|png)$ { ... } # 正则(不区分大小写)
location / { ... } # 通用前缀
5. 静态站点托管
server {
listen 80;
server_name static.example.com;
root /data/www/static-site;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
root:拼接 URI 找文件try_files:优先返回真实文件,否则回退(SPA 必备)
6. 反向代理(最常用)
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
关键点:
proxy_pass指向上游服务- 通过
X-Forwarded-*传递原始请求信息 - 后端如果要拿到真实客户端 IP,需要信任这些头
7. 负载均衡
7.1 轮询(默认)
upstream app_pool {
server 10.0.0.11:8080;
server 10.0.0.12:8080;
server 10.0.0.13:8080;
}
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://app_pool;
}
}
7.2 权重、故障处理
upstream app_pool {
server 10.0.0.11:8080 weight=5;
server 10.0.0.12:8080 weight=3;
server 10.0.0.13:8080 weight=2 max_fails=3 fail_timeout=30s;
}
7.3 会话保持(IP Hash)
upstream app_pool {
ip_hash;
server 10.0.0.11:8080;
server 10.0.0.12:8080;
}
8. HTTPS / TLS 配置
server {
listen 443 ssl http2;
server_name www.example.com;
ssl_certificate /etc/nginx/ssl/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
location / {
proxy_pass http://127.0.0.1:3000;
}
}
server {
listen 80;
server_name www.example.com;
return 301 https://$host$request_uri;
}
证书可用 Let's Encrypt(certbot)自动签发与续期。
9. 重写与跳转(rewrite/return)
9.1 永久跳转
location = /old-page {
return 301 /new-page;
}
9.2 rewrite 示例
location /blog/ {
rewrite ^/blog/(.*)$ /articles/$1 permanent;
}
return简洁高效,优先使用rewrite更灵活,适合复杂规则
10. 缓存(静态缓存 + 代理缓存)
10.1 浏览器缓存(静态文件)
location ~* \.(js|css|png|jpg|jpeg|gif|svg|woff2?)$ {
expires 30d;
add_header Cache-Control "public, max-age=2592000, immutable";
}
10.2 反向代理缓存
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api_cache:100m inactive=60m max_size=2g;
server {
listen 80;
server_name cache.example.com;
location / {
proxy_cache api_cache;
proxy_cache_key $scheme$proxy_host$request_uri;
proxy_cache_valid 200 10m;
proxy_cache_valid 404 1m;
add_header X-Cache-Status $upstream_cache_status;
proxy_pass http://127.0.0.1:3000;
}
}
11. 压缩与传输优化
11.1 Gzip
gzip on;
gzip_comp_level 5;
gzip_min_length 1k;
gzip_types text/plain text/css application/javascript application/json application/xml image/svg+xml;
gzip_vary on;
11.2 Brotli(需安装模块)
brotli on;
brotli_comp_level 5;
brotli_types text/plain text/css application/javascript application/json image/svg+xml;
12. 跨域 CORS
location /api/ {
if ($request_method = OPTIONS) {
add_header Access-Control-Allow-Origin "*" always;
add_header Access-Control-Allow-Methods "GET,POST,PUT,DELETE,OPTIONS" always;
add_header Access-Control-Allow-Headers "Content-Type,Authorization" always;
add_header Access-Control-Max-Age 86400 always;
return 204;
}
add_header Access-Control-Allow-Origin "*" always;
proxy_pass http://127.0.0.1:3000;
}
生产建议将
*换成白名单域名。
13. 访问控制与基础认证
13.1 IP 白名单
location /admin/ {
allow 10.0.0.0/8;
deny all;
proxy_pass http://127.0.0.1:8080;
}
13.2 Basic Auth
location /private/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
14. 限流与连接数限制(防刷/防爆破)
http {
limit_req_zone $binary_remote_addr zone=req_zone:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn_zone:10m;
server {
listen 80;
server_name protect.example.com;
location /api/ {
limit_req zone=req_zone burst=20 nodelay;
limit_conn conn_zone 20;
proxy_pass http://127.0.0.1:3000;
}
}
}
15. 错误页与自定义返回
server {
listen 80;
server_name err.example.com;
root /data/www/error-pages;
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html { }
location = /404.html { }
}
API 场景可直接返回 JSON:
location /healthz {
default_type application/json;
return 200 '{"status":"ok"}';
}
16. 日志与可观测性
http {
log_format json escape=json
'{'
'"time":"$time_iso8601",'
'"remote_addr":"$remote_addr",'
'"request":"$request",'
'"status":$status,'
'"body_bytes_sent":$body_bytes_sent,'
'"request_time":$request_time,'
'"upstream_time":"$upstream_response_time",'
'"ua":"$http_user_agent"'
'}';
access_log /var/log/nginx/access.log json;
error_log /var/log/nginx/error.log warn;
}
常排查命令:
nginx -t
tail -f /var/log/nginx/error.log
tail -f /var/log/nginx/access.log
17. WebSocket 代理
location /ws/ {
proxy_pass http://127.0.0.1:3001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}
18. 文件上传与请求体限制
server {
listen 80;
server_name upload.example.com;
client_max_body_size 50m;
client_body_timeout 60s;
location /upload {
proxy_read_timeout 300s;
proxy_pass http://127.0.0.1:3000;
}
}
19. 性能常用参数
worker_processes auto;
worker_rlimit_nofile 65535;
events {
use epoll;
worker_connections 4096;
multi_accept on;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 1000;
types_hash_max_size 2048;
}
20. 反向代理超时与故障切换
location / {
proxy_connect_timeout 3s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 3;
proxy_pass http://app_pool;
}
21. 多环境配置组织建议
推荐目录组织:
nginx.conf:全局基础配置conf.d/common/*.conf:通用片段(gzip、ssl、log)conf.d/sites/*.conf:站点配置conf.d/upstreams/*.conf:后端池配置
可复用片段示例:
# /etc/nginx/snippets/proxy_common.conf
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
使用:
location /api/ {
include /etc/nginx/snippets/proxy_common.conf;
proxy_pass http://app_pool;
}
22. 安全加固清单
- 隐藏版本号:
server_tokens off; - 仅开放必要端口(80/443)
- 强制 HTTPS,启用 HSTS(确认全站 HTTPS 后)
- 上传大小与速率限制
- 配置防盗链(按需)
- 定期升级 Nginx 与 OpenSSL
- 证书自动续期监控
HSTS 示例:
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
23. Stream 模块(TCP/UDP 转发)
适用于 MySQL、Redis、MQTT 等四层转发(需已编译
stream)。
stream {
upstream mysql_backend {
server 10.0.0.21:3306;
server 10.0.0.22:3306;
}
server {
listen 3307;
proxy_pass mysql_backend;
}
}
24. 邮件代理(mail 模块,较少用)
Nginx 支持 IMAP/POP3/SMTP 代理(需 mail 模块),现代生产使用较少。若需要可按官方文档启用 mail {} 配置块。
25. 常见问题排查
25.1 502 Bad Gateway
可能原因:
- 后端没启动或端口错误
- 防火墙阻断
- upstream 超时
- Unix socket 权限问题
排查顺序:
nginx -t- 看
error.log curl后端地址确认可达- 核对
proxy_pass、超时参数
25.2 404 但文件存在
- 检查
root/alias用法是否混淆 - 检查
location匹配是否进入预期块 - 检查文件系统权限
25.3 重载失败
nginx -t && nginx -s reload
先测语法再重载。
26. root 与 alias 区别(高频坑)
location /img/ {
root /data/www;
}
请求 /img/a.png -> 实际文件:/data/www/img/a.png
location /img/ {
alias /data/assets/;
}
请求 /img/a.png -> 实际文件:/data/assets/a.png
27. SPA、前后端分离与 API 网关示例
server {
listen 80;
server_name demo.example.com;
root /data/www/spa;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location /api/ {
include /etc/nginx/snippets/proxy_common.conf;
proxy_pass http://127.0.0.1:8080/;
}
}
28. Docker 部署示例
Dockerfile:
FROM nginx:stable-alpine
COPY ./dist /usr/share/nginx/html
COPY ./nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
运行:
docker build -t my-nginx-app .
docker run -d -p 8080:80 --name my-nginx my-nginx-app
29. 生产上线建议流程
- 本地验证配置:
nginx -t - 灰度环境验证:功能、性能、日志
- 备份旧配置
- 发布新配置并
reload - 观察错误率、延迟、CPU、连接数
- 异常快速回滚
30. 一份可直接改造的综合模板
upstream backend {
server 127.0.0.1:8080;
keepalive 32;
}
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/nginx/ssl/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
root /data/www/spa;
index index.html;
# 安全头(按需调整)
add_header X-Frame-Options SAMEORIGIN always;
add_header X-Content-Type-Options nosniff always;
add_header Referrer-Policy no-referrer-when-downgrade always;
# 静态缓存
location ~* \.(js|css|png|jpg|jpeg|gif|svg|woff2?)$ {
expires 30d;
add_header Cache-Control "public, max-age=2592000, immutable";
}
# 前端路由
location / {
try_files $uri $uri/ /index.html;
}
# API 反代
location /api/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
31. 学习路线建议
- 第 1 阶段:静态站点 + 反向代理 + HTTPS
- 第 2 阶段:负载均衡 + 缓存 + 限流
- 第 3 阶段:日志治理 + 性能调优 + 安全加固
- 第 4 阶段:容器化 + 自动化发布 + 可观测性体系
32. 官方文档
如果你需要,我可以继续在这份文档后面追加:
- 按“前端项目部署 / Java 项目 / Node 项目 / Go 项目”四套完整配置
- 一份“企业生产默认基线配置”
- 常见面试题版(含答案)