Nginx 命令速查表
Nginx 是高性能的 Web 服务器和反向代理服务器,以高并发、低内存占用和灵活的配置语法著称。本速查表覆盖了日常运维和开发中最常用的 Nginx 配置指令,包括 location 规则匹配、SSL 证书配置、反向代理、缓存策略、URL 重写、负载均衡以及日志管理。建议从 location 和 proxy 配置入手,逐步深入 SSL 和缓存优化。
使用场景速查
| 你要做什么 | 配置指令 |
| 静态文件服务 | root /var/www/html; + index index.html; |
| URL 重定向 | return 301 https://$host$request_uri; |
| 反向代理 | proxy_pass http://backend; |
| 负载均衡 | upstream backend { server ...; } |
| HTTPS 配置 | listen 443 ssl; + ssl_certificate |
| URL 重写 | rewrite ^/old/(.*)$ /new/$1 permanent; |
| 限速配置 | limit_req zone=mylimit burst=10; |
| 缓存启用 | proxy_cache mycache; |
| 访问控制 | allow 192.168.1.0/24; deny all; |
| 配置检查 | nginx -t |
Location 匹配
``nginx
# 精确匹配(最高优先级)
location = / {
return 200 "Welcome to root!\n";
}
# 精确匹配特定路径 location = /favicon.ico { log_not_found off; access_log off; }
# 前缀匹配(匹配后不再检查正则——^~ 修饰) location ^~ /static/ { root /var/www; expires 30d; }
# 正则匹配(区分大小写) location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; }
# 正则匹配(忽略大小写) location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { root /var/www; expires max; add_header Cache-Control "public, immutable"; }
# 普通前缀匹配(最长匹配优先) location /api/ { proxy_pass http://api_backend; }
location / { root /var/www/html; index index.html; }
# 命名 location(内部跳转用,不对外暴露) location @fallback { proxy_pass http://backend; }
# 嵌套 location location /app/ { location ~ \.php$ { fastcgi_pass unix:/var/run/php.sock; } }
# 别名路径映射 location /images/ { alias /data/uploads/; # /images/foo.jpg → /data/uploads/foo.jpg }
# 访问控制 location /admin/ { allow 192.168.1.0/24; allow 10.0.0.0/8; deny all; }
# try_files 组合
location / {
try_files $uri $uri/ /index.html; # SPA 回退模式
}
`
SSL/TLS 配置
`nginx
# HTTPS server 基本配置
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com.pem; ssl_certificate_key /etc/nginx/ssl/example.com.key;
# 协议与加密套件 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;
# DH 参数(提升安全性) ssl_dhparam /etc/nginx/ssl/dhparam.pem;
# HSTS(强制 HTTPS) add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# OCSP Stapling ssl_stapling on; ssl_stapling_verify on; resolver 8.8.8.8 8.8.4.4 valid=300s; resolver_timeout 5s;
# 会话缓存 ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; ssl_session_tickets off; }
# HTTP → HTTPS 跳转 server { listen 80; server_name example.com www.example.com; return 301 https://$host$request_uri; }
# 双向 TLS(客户端证书认证) server { listen 443 ssl; ssl_client_certificate /etc/nginx/ssl/ca.crt; ssl_verify_client on; ssl_verify_depth 2;
location / { if ($ssl_client_verify != SUCCESS) { return 403; } proxy_pass http://backend; } }
# Let's Encrypt 自动续签
location ^~ /.well-known/acme-challenge/ {
root /var/www/html;
}
`
反向代理
`nginx
# 基本反向代理
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_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }
# WebSocket 代理 location /ws/ { proxy_pass http://ws_backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_read_timeout 86400s; # 长连接超时 }
# 路径重写 + 代理 location /app/ { rewrite ^/app/(.*)$ /$1 break; proxy_pass http://app_server; # 避免 /app/foo → /app/foo(去掉前缀) }
# 代理缓冲区控制 location /api/ { proxy_pass http://api_server; proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 4k; proxy_busy_buffers_size 8k; proxy_max_temp_file_size 0; }
# 超时设置 location /slow/ { proxy_pass http://slow_backend; proxy_connect_timeout 10s; proxy_read_timeout 30s; proxy_send_timeout 30s; }
# 错误页面覆盖
location / {
proxy_pass http://backend;
proxy_intercept_errors on;
error_page 502 503 504 /50x.html;
}
`
缓存策略
`nginx
# 定义缓存区(http 块中)
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=mycache:10m max_size=1g inactive=60m use_temp_path=off;
# 后端缓存控制 proxy_cache_key "$scheme$request_method$host$request_uri"; proxy_cache mycache;
# 按响应码设置缓存时间 proxy_cache_valid 200 302 60m; proxy_cache_valid 301 24h; proxy_cache_valid 404 1m; proxy_cache_valid any 5m;
# 缓存绕过 proxy_cache_bypass $http_cache_control; proxy_no_cache $http_pragma $http_authorization;
# 缓存锁定(防止缓存雪崩) proxy_cache_lock on; proxy_cache_lock_timeout 5s;
# 缓存命中调试 add_header X-Cache-Status $upstream_cache_status;
# 正向代理缓存 location / { proxy_pass http://origin; proxy_cache public_cache; proxy_cache_valid 200 1h; proxy_cache_use_stale error timeout updating http_500 http_502 http_503;
# 清除缓存(配合反向代理使用) location ~ /purge(/.*) { allow 127.0.0.1; deny all; proxy_cache_purge mycache "$scheme$request_method$host$1"; } }
# 按参数分区缓存 proxy_cache_key "$scheme$host$request_uri$is_args$args";
# 微缓存(针对动态内容) location / { proxy_cache micro; proxy_cache_valid 200 5s; proxy_cache_lock on; }
# FastCGI 缓存
fastcgi_cache_path /data/nginx/fastcgi_cache levels=1:2 keys_zone=phpcache:10m max_size=1g inactive=60m;
location ~ \.php$ {
fastcgi_cache phpcache;
fastcgi_cache_valid 200 60m;
fastcgi_cache_methods GET HEAD;
fastcgi_cache_use_stale error timeout updating;
}
`
URL 重写与重定向
`nginx
# 永久重定向
rewrite ^/old-page$ /new-page permanent;
rewrite ^/category/(.*)$ /shop/category/$1 permanent;
# 临时重定向 rewrite ^/temp$ /temporary redirect;
# 内部重写(URL 不变) rewrite ^/articles/(\d+)$ /show.php?id=$1 last; rewrite ^/user/([a-z]+)$ /profile.php?name=$1 last;
# 协议重定向 if ($scheme != "https") { return 301 https://$server_name$request_uri; }
# 去除 www if ($host ~* ^www\.(.*)) { set $host_no_www $1; return 301 $scheme://$host_no_www$request_uri; }
# 添加 www if ($host !~* ^www\.) { return 301 $scheme://www.$host$request_uri; }
# URI 参数处理 if ($args ~* "utm_source|utm_medium|utm_campaign") { return 301 $scheme://$host$uri; }
# 尾部斜杠处理 rewrite ^([^.]*[^/])$ $1/ permanent;
# 文件扩展名映射 location ~ \.php$ { rewrite ^(.*)$ /index.php?$1 last; }
# 自定义错误页面
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /var/www/html;
}
`
上游服务器与负载均衡
`nginx
# HTTP 负载均衡
upstream backend {
# 默认轮询策略
server 192.168.1.10:3000 weight=3 max_fails=3 fail_timeout=30s;
server 192.168.1.11:3000 weight=2 max_fails=3 fail_timeout=30s;
server 192.168.1.12:3000 backup; # 备用服务器
server unix:/var/run/app.sock; # Unix Socket
keepalive 32; # 保持连接池 }
# IP Hash 会话保持 upstream sticky_backend { ip_hash; server 192.168.1.10:3000; server 192.168.1.11:3000; }
# 最少连接 upstream least_conn_backend { least_conn; server 192.168.1.10:3000; server 192.168.1.11:3000; }
# 随机策略 upstream random_backend { random two least_conn; server 192.168.1.10:3000; server 192.168.1.11:3000; server 192.168.1.12:3000; }
# 健康检查(需要商业版或 nginx-plus,开源版用被动检查) # 被动健康检查由 max_fails + fail_timeout 控制
# 灰度发布(通过上游权重调整) upstream canary { server 192.168.1.10:3000 weight=90; # 稳定版 90% server 192.168.1.20:3000 weight=10; # 灰度 10% }
# 使用 map 实现分流 map $cookie_user $backend_group { default backend; ~^admin admin_backend; }
# 上游服务器超时和重试
location / {
proxy_pass http://backend;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
proxy_next_upstream_timeout 10s;
proxy_next_upstream_tries 3;
}
`
日志管理
`nginx
# 自定义日志格式
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
# JSON 格式日志(方便日志分析工具) log_format json escape=json '{' '"time_local":"$time_local",' '"remote_addr":"$remote_addr",' '"remote_user":"$remote_user",' '"request":"$request",' '"status":$status,' '"body_bytes_sent":$body_bytes_sent,' '"request_time":"$request_time",' '"http_referrer":"$http_referer",' '"http_user_agent":"$http_user_agent",' '"http_x_forwarded_for":"$http_x_forwarded_for"' '}';
# 缓存命中/未命中日志 log_format cache '$remote_addr - $upstream_cache_status [$time_local] "$request" $status'; }
# 访问日志 access_log /var/log/nginx/access.log main; access_log /var/log/nginx/json.log json;
# 错误日志 error_log /var/log/nginx/error.log warn;
# 按站点分离日志 server { access_log /var/log/nginx/example.com.access.log main buffer=32k flush=5s; error_log /var/log/nginx/example.com.error.log error; }
# 关闭特定 location 的日志 location = /health { access_log off; return 200 "OK\n"; }
location = /favicon.ico { access_log off; log_not_found off; }
# 条件日志记录 map $status $loggable { ~^[23] 0; # 2xx 和 3xx 不记录 default 1; # 其他记录 } access_log /var/log/nginx/error_only.log main if=$loggable;
# 日志轮转(nginx -s reopen 触发)
# 配合 logrotate 使用:
# /var/log/nginx/*.log {
# daily
# rotate 30
# compress
# postrotate
# [ ! -f /var/run/nginx.pid ] || kill -USR1 cat /var/run/nginx.pid
# endscript
# }
# 请求体记录限制 client_body_buffer_size 128k; client_max_body_size 10m;
# 调试日志(仅调试时启用) # error_log /var/log/nginx/debug.log debug; ``
Location 匹配(8)
| 命令 | 难度 | ||
|---|---|---|---|
location = /path { ... }精确匹配指定路径(最高优先级) | 基础 | location = /favicon.ico { log_not_found off; } | |
location ^~ /path/ { ... }前缀匹配,匹配后不再检查正则表达式 | 中级 | location ^~ /static/ { root /var/www; } | |
location ~ pattern { ... }正则匹配(区分大小写) | 中级 | location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; } | |
location ~* pattern { ... }正则匹配(不区分大小写) | 中级 | location ~* \.(jpg|png|css|js)$ { expires max; } | |
location /path/ { ... }普通前缀匹配(最长匹配优先) | 基础 | location /api/ { proxy_pass http://backend; } | |
location @name { ... }命名 location(内部跳转,不对外暴露) | 中级 | location @fallback { proxy_pass http://backend; } | |
alias <path>将请求路径映射到不同的文件系统路径 | 中级 | location /images/ { alias /data/uploads/; } | |
try_files $uri $uri/ /index.html按顺序尝试文件/目录,都不存在则回退到最后一项 | 基础 | try_files $uri $uri/ /index.html |
SSL/TLS 配置(7)
| 命令 | 难度 | ||
|---|---|---|---|
listen 443 ssl http2监听 443 端口并启用 SSL 和 HTTP/2 | 基础 | listen 443 ssl http2 | |
ssl_certificate / ssl_certificate_key指定 SSL 证书和私钥文件路径 | 基础 | ssl_certificate /etc/nginx/ssl/example.com.pem | |
ssl_protocols TLSv1.2 TLSv1.3指定允许的 SSL/TLS 协议版本(禁用旧版) | 中级 | ssl_protocols TLSv1.2 TLSv1.3 | |
ssl_ciphers <cipher_list>指定 SSL 加密套件 | 高级 | ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384 | |
add_header Strict-Transport-Security启用 HSTS,强制浏览器使用 HTTPS 访问 | 中级 | add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always | |
ssl_session_cache shared:SSL:10m配置 SSL 会话缓存(减少重复握手) | 中级 | ssl_session_cache shared:SSL:10m | |
return 301 https://$host$request_uriHTTP 自动跳转 HTTPS | 基础 | return 301 https://$host$request_uri |
反向代理(5)
| 命令 | 难度 | ||
|---|---|---|---|
proxy_pass <url>将请求转发到后端服务器 | 基础 | proxy_pass http://127.0.0.1:3000 | |
proxy_set_header <field> <value>设置转发给后端的 HTTP 请求头 | 基础 | proxy_set_header X-Real-IP $remote_addr | |
proxy_http_version 1.1设置代理 HTTP 协议版本(WebSocket 等需要) | 中级 | proxy_http_version 1.1 | |
proxy_read_timeout 30s设置代理读取超时时间 | 中级 | proxy_read_timeout 30s | |
proxy_intercept_errors on拦截后端错误状态码并显示自定义错误页 | 中级 | proxy_intercept_errors on |
缓存策略(5)
| 命令 | 难度 | ||
|---|---|---|---|
proxy_cache_path <path> <options>定义缓存存储路径和参数 | 高级 | proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=mycache:10m max_size=1g inactive=60m | |
proxy_cache <zone>启用代理缓存并指定缓存区 | 中级 | proxy_cache mycache | |
proxy_cache_valid 200 302 60m按响应状态码设置缓存有效期 | 中级 | proxy_cache_valid 200 302 60m | |
proxy_cache_bypass <condition>指定绕过缓存的条件 | 中级 | proxy_cache_bypass $http_cache_control | |
add_header X-Cache-Status $upstream_cache_status在响应头中添加缓存命中状态(调试用) | 中级 | add_header X-Cache-Status $upstream_cache_status |
URL 重写(7)
| 命令 | 难度 | ||
|---|---|---|---|
rewrite ^/old$ /new permanent永久重定向(301) | 基础 | rewrite ^/old-page$ /new-page permanent | |
rewrite ^/temp$ /temporary redirect临时重定向(302) | 基础 | rewrite ^/temp$ /temporary redirect | |
rewrite ^/path/(.*)$ /new/$1 last内部 URL 重写(浏览器 URL 不变) | 中级 | rewrite ^/articles/(\d+)$ /show.php?id=$1 last | |
return 301 https://$server_name$request_uri返回指定状态码和重定向 URL | 基础 | return 301 https://$server_name$request_uri | |
if ($scheme != "https") { ... }条件判断(在重写中使用) | 中级 | if ($scheme != "https") { return 301 https://$server_name$request_uri; } | |
error_page 404 /404.html自定义错误页面 | 基础 | error_page 404 /404.html | |
rewrite ^([^.]*[^/])$ $1/ permanent自动添加尾部斜杠 | 中级 | rewrite ^([^.]*[^/])$ $1/ permanent |
上游服务器(5)
| 命令 | 难度 | ||
|---|---|---|---|
upstream name { server ...; }定义上游服务器组(后端服务器池) | 基础 | upstream backend { server 192.168.1.10:3000; } | |
server <address> weight=<n>在 upstream 中添加后端服务器及权重 | 中级 | server 192.168.1.10:3000 weight=3 max_fails=3 fail_timeout=30s | |
server <address> backup设置备用服务器(仅当主服务器不可用时启用) | 中级 | server 192.168.1.12:3000 backup | |
ip_hash启用 IP 哈希负载均衡(保持会话亲和性) | 中级 | ip_hash | |
least_conn启用最少连接负载均衡策略 | 中级 | least_conn |
日志管理(5)
| 命令 | 难度 | ||
|---|---|---|---|
log_format <name> <format>定义自定义日志格式 | 中级 | log_format json escape=json {"time":"$time_local","status":$status} | |
access_log <file> <format>配置访问日志文件路径和格式 | 基础 | access_log /var/log/nginx/access.log main | |
error_log <file> <level>配置错误日志文件路径和级别 | 基础 | error_log /var/log/nginx/error.log warn | |
access_log off关闭指定 location 的访问日志 | 基础 | location = /health { access_log off; } | |
client_max_body_size <size>设置客户端请求体的最大大小 | 基础 | client_max_body_size 10m |