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; |
pid | PID 文件路径 | 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 | 禁用 Nagle | tcp_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; |
rewrite | URL 重写 | rewrite ^/old/(.*)$ /new/$1; |
proxy_pass | 反向代理 | proxy_pass http://backend; |
fastcgi_pass | FastCGI 代理 | 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_agent | User-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