跳到主要内容

Nginx 知识速查表

本页面汇总了 Nginx 最常用的命令和配置,方便快速查阅。

基本命令

服务管理

# 启动
nginx
systemctl start nginx

# 停止
nginx -s stop # 快速停止
nginx -s quit # 优雅停止
systemctl stop nginx

# 重启
systemctl restart nginx

# 重新加载配置(不中断服务)
nginx -s reload
systemctl reload nginx

# 检查配置语法
nginx -t

# 查看版本
nginx -v
nginx -V # 显示编译参数

进程管理

# 查看进程
ps aux | grep nginx
pgrep nginx

# 杀掉进程
kill -QUIT $(cat /var/run/nginx.pid) # 优雅停止
kill -TERM $(cat /var/run/nginx.pid) # 快速停止
kill -HUP $(cat /var/run/nginx.pid) # 重新加载

配置结构

main        # 全局配置
├── events # 事件模型配置
├── http # HTTP 服务配置
│ ├── upstream # 上游服务器组
│ └── server # 虚拟主机
│ └── location # URL 匹配规则
└── mail # 邮件代理(可选)

常用指令速查

全局指令

指令说明示例
worker_processes工作进程数worker_processes auto;
worker_connections每进程最大连接数worker_connections 1024;
user运行用户user nginx;
error_log错误日志error_log /var/log/nginx/error.log warn;
pidPID 文件路径pid /var/run/nginx.pid;

HTTP 指令

指令说明示例
include包含配置文件include mime.types;
default_type默认 MIME 类型default_type application/octet-stream;
sendfile高效文件传输sendfile on;
tcp_nopush合并数据包tcp_nopush on;
tcp_nodelay禁用 Nagletcp_nodelay on;
keepalive_timeout保持连接超时keepalive_timeout 65;
gzip开启压缩gzip on;
client_max_body_size最大请求体client_max_body_size 8m;

Server 指令

指令说明示例
listen监听端口listen 80;
server_name服务器名称server_name example.com;
root网站根目录root /var/www/html;
index默认首页index index.html;
charset默认编码charset utf-8;
access_log访问日志access_log /var/log/nginx/access.log;

Location 指令

指令说明示例
alias目录别名alias /var/www/images/;
try_files尝试文件try_files $uri $uri/ /index.html;
return返回状态码/重定向return 301 https://$host$request_uri;
rewriteURL 重写rewrite ^/old/(.*)$ /new/$1;
proxy_pass反向代理proxy_pass http://backend;
fastcgi_passFastCGI 代理fastcgi_pass 127.0.0.1:9000;

Location 匹配规则

# 精确匹配
location = / {
# 只匹配 /
}

# 前缀匹配(优先级最高)
location ^~ /images/ {
# 匹配 /images/ 开头
}

# 正则匹配(区分大小写)
location ~ \.php$ {
# 匹配 .php 结尾
}

# 正则匹配(不区分大小写)
location ~* \.(jpg|png|gif)$ {
# 匹配图片
}

# 普通前缀匹配
location /api/ {
# 匹配 /api/ 开头
}

# 默认匹配
location / {
# 匹配所有
}

优先级= > ^~ > ~/~* > 普通前缀 > /

反向代理

upstream backend {
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}

server {
location / {
proxy_pass http://backend;

# 代理头
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_connect_timeout 60s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
}
}

负载均衡

# 轮询(默认)
upstream backend {
server 192.168.1.101:8080;
server 192.168.1.102:8080;
}

# 加权轮询
upstream backend {
server 192.168.1.101:8080 weight=3;
server 192.168.1.102:8080 weight=1;
}

# IP Hash
upstream backend {
ip_hash;
server 192.168.1.101:8080;
server 192.168.1.102:8080;
}

# 最少连接
upstream backend {
least_conn;
server 192.168.1.101:8080;
server 192.168.1.102:8080;
}

# 服务器参数
server 192.168.1.101:8080 weight=3 max_fails=3 fail_timeout=30s backup down;

SSL/TLS

server {
listen 443 ssl http2;

# 证书
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;

# 协议和加密
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers off;

# 会话缓存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;

# HTTP 重定向到 HTTPS
add_header Strict-Transport-Security "max-age=63072000" always;
}

Gzip 压缩

gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 256;
gzip_types
text/plain
text/css
text/xml
application/json
application/javascript
application/xml
image/svg+xml;

缓存配置

# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}

# 代理缓存
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g;

server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating;
}
}

日志配置

# 日志格式
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;

# 关闭日志
access_log off;

# 条件日志
map $status $is_error {
~^[45] 1;
default 0;
}
access_log /var/log/nginx/error.log main if=$is_error;

内置变量

变量说明
$remote_addr客户端 IP
$remote_user客户端用户名
$request_method请求方法
$request_uri完整请求 URI
$uri请求 URI(不带参数)
$args查询参数
$host主机名
$server_name服务器名称
$server_port服务器端口
$scheme协议(http/https)
$http_user_agentUser-Agent
$http_referer来源页面
$status响应状态码
$body_bytes_sent发送字节数
$upstream_addr后端服务器地址
$upstream_response_time后端响应时间
$request_id请求 ID

安全配置

# 隐藏版本
server_tokens off;

# 安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'" always;

# 限制请求方法
if ($request_method !~ ^(GET|POST|HEAD)$) {
return 405;
}

# 禁止访问隐藏文件
location ~ /\. {
deny all;
}

# 限制 IP
allow 192.168.1.0/24;
deny all;

限流配置

# 定义限流区域
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

server {
location /api/ {
limit_req zone=api burst=20 nodelay;
}
}

# 限制连接数
limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
location / {
limit_conn addr 10;
}
}

错误页面

# 自定义错误页面
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;

location = /404.html {
root /var/www/errors;
internal;
}

location = /50x.html {
root /var/www/errors;
internal;
}

常见配置模板

静态网站

server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html;

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

location ~* \.(jpg|jpeg|png|gif|css|js|woff2)$ {
expires 30d;
}
}

SPA 应用

server {
listen 80;
server_name example.com;
root /var/www/spa/dist;
index index.html;

location / {
try_files $uri $uri/ /index.html;
}

location /api/ {
proxy_pass http://127.0.0.1:3000;
}
}

Node.js 代理

upstream nodejs {
server 127.0.0.1:3000;
keepalive 32;
}

server {
listen 80;
server_name example.com;

location / {
proxy_pass http://nodejs;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}

PHP-FPM

server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html;

location / {
try_files $uri $uri/ /index.php?$args;
}

location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}

调试技巧

# 测试配置
nginx -t

# 查看生效配置
nginx -T

# 实时查看日志
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log

# 检查端口占用
netstat -tlnp | grep nginx
ss -tlnp | grep nginx

# 测试连接
curl -I http://localhost
curl -v https://example.com