Nginx 全面实战生产运维指南(持续更新)
前言
Nginx 是什么?
想象一下:你开了一家大型餐厅,需要接待大量客人(用户请求)。
如果让客人直接进入厨房找厨师(后端服务器),会出现什么问题?
- 客人找不到路(请求不知道去哪台服务器)
- 厨房太拥挤(服务器压力大)
- 一个厨师忙死,其他厨师闲着(负载不均)
Nginx 就是这家餐厅的"超级前台接待"! 它站在门口:
- 接收所有客人(接收请求)
- 智能分配客人到不同的厨师(负载均衡)
- 有时候还帮忙处理一些简单的事(静态资源服务)
- 复杂的事才交给后厨(动态请求代理)
这就是 Nginx 的魔力:高性能、高并发、稳如老狗!
Nginx 是互联网最常用的 Web 服务器和反向代理服务器,作为运维工程师,我们的职责是:让它快如闪电、稳如磐石。
本文档会告诉你:
- Nginx 核心概念和原理
- 常用配置详解
- 性能优化技巧
- 日志分析
- HTTPS 配置
- 常见问题排查
目录
快速入门
Nginx 基本概念
| 概念 | 通俗解释 | 类比 |
|---|---|---|
| Web 服务器 | 提供网页内容 | 餐厅服务员,上菜 |
| 反向代理 | 接收请求转发给后端 | 前台接待,分配客人 |
| 负载均衡 | 分配请求到多台服务器 | 领位员,轮流分配 |
| 动静分离 | 静态和动态分开处理 | 前台处理简单事,后厨处理复杂事 |
安装 Nginx
# 👀 Ubuntu/Debian 安装
sudo apt update
sudo apt install nginx
# 👀 CentOS/RHEL 安装
sudo yum install epel-release
sudo yum install nginx
# 👀 启动 Nginx
sudo systemctl start nginx
# 👀 设置开机启动
sudo systemctl enable nginx
# 👀 查看状态
sudo systemctl status nginx
# 👀 测试访问
curl http://localhost
Nginx 目录结构
# 👀 查看 Nginx 安装目录
ls -la /etc/nginx/
# 输出:
# nginx.conf # 主配置文件
# conf.d/ # 额外配置目录
# sites-enabled/ # 启用的站点
# sites-available/ # 可用的站点
# modules-enabled/ # 启用的模块
# 👀 查看网页目录
ls -la /var/www/html/
# 输出:
# index.nginx-debian.html # 默认页面
验证 Nginx
# 👀 查看 Nginx 版本
nginx -v
# 👀 查看详细版本信息
nginx -V
# 输出示例:
# nginx version: nginx/1.24.0
# built with OpenSSL 3.0.x
# TLS SNI support enabled
核心概念详解
1. 正向代理 vs 反向代理
什么是代理?
想象一下:你委托秘书帮你处理事务。
正向代理:你让秘书帮你去买东西(代理你的请求),卖家不知道是谁买的
反向代理:客户来公司找客服,客服帮你转接(代理服务器的响应),客户不知道是哪位员工处理的
正向代理(Forward Proxy):
用户 → 代理服务器 → 目标网站
(帮用户隐藏身份)
反向代理(Reverse Proxy):
用户 → Nginx → 后端服务器1
→ 后端服务器2
→ 后端服务器3
(帮服务器隐藏身份和分发请求)
| 类型 | 代理谁 | 隐藏谁 | 用途 |
|---|---|---|---|
| 正向代理 | 客户端 | 用户 | 翻墙、缓存 |
| 反向代理 | 服务端 | 后端服务器 | 负载均衡、安全 |
2. 负载均衡
什么是负载均衡?
想象一下:餐厅有 3 位厨师,高峰期来了 100 位客人。
- 如果让客人自己选厨师:A厨师忙死,B、C厨师闲着
- 如果让接待员分配客人:轮流分配,大家工作均匀
负载均衡就是这个"智能接待员"!
Nginx 负载均衡算法:
| 算法 | 通俗解释 | 适用场景 |
|---|---|---|
| 轮询(Round Robin) | 轮流分配 | 服务器配置相近 |
| 加权轮询(Weighted) | 能者多劳 | 服务器性能不同 |
| 最少连接(Least Connections) | 谁空闲找谁 | 请求耗时不同 |
| IP 哈希(IP Hash) | 固定 IP 找固定服务器 | 需要会话保持 |
| URL 哈希(URL Hash) | 相同 URL 找相同服务器 | 缓存友好 |
3. 动静分离
什么是动静分离?
想象一下:餐厅里有些事很简单(前台接待、点单),有些事很复杂(炒菜、煲汤)。
- 如果让厨师去做所有事,包括简单的点单和复杂的炒菜,效率会很低
- 如果让接待员处理简单的点单,厨师只做复杂的炒菜,效率会大大提高
动静分离就是这样!
- 静态资源(HTML、CSS、JS、图片):Nginx 直接返回
- 动态请求(API、数据查询):转发给后端处理
分离的好处:
- 提高响应速度
- 减轻后端压力
- 更好的缓存策略
- 更灵活的扩展
4. 工作原理
Nginx 是怎么工作的?
Nginx 就像一个超级高效的前台团队:
Master 进程:前台经理,负责管理监督
- 读取配置文件
- 管理工作进程
- 处理信号(重启、停止)
Worker 进程:一线员工,实际干活
- 处理客户端请求
- 返回响应内容
- 监控连接状态
┌─────────────────────────────────────────┐
│ Master 进程 │
│ (经理:管理、监督、重启) │
│ PID: 1234 │
└────────────────┬────────────────────────┘
│
┌────────────┼────────────┐
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│ Worker │ │ Worker │ │ Worker │
│ 进程1 │ │ 进程2 │ │ 进程3 │
│(员工1) │ │(员工2) │ │(员工3) │
└────────┘ └────────┘ └────────┘
│ │ │
▼ ▼ ▼
处理请求 → 处理请求 → 处理请求
Nginx 的优势:
- 事件驱动:一个 Worker 可以处理成千上万的连接
- 异步非阻塞:不会因为一个请求卡住而影响其他请求
- 多进程:Worker 进程之间相互独立,一个崩溃不影响其他
5. 配置文件的结构
Nginx 配置文件就像餐厅的组织架构图:
# nginx.conf(公司组织架构)
# 全局块:公司的基本规定
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
# events 块:会议室规则
events {
worker_connections 1024; # 每个员工能接待多少人
}
# http 块:公司主营业务
http {
# http 全局块:整个公司的政策
include /etc/nginx/mime.types;
default_type application/octet-stream;
# server 块:某个部门
server {
# server 全局块:部门规定
listen 80;
server_name example.com;
# location 块:某个职位的工作
location / {
root /var/www/html;
index index.html;
}
# 另一个职位
location /api {
proxy_pass http://backend;
}
}
}
配置详解
1. 最小配置示例
# 👀 最小配置的 Nginx
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html;
}
}
2. 反向代理配置
# 👀 反向代理到后端服务器
server {
listen 80;
server_name myapp.example.com;
location / {
# 代理到后端地址
proxy_pass http://127.0.0.1:8080;
# 传递真实 IP 给后端
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_send_timeout 60s;
proxy_read_timeout 60s;
}
}
3. 负载均衡配置
# 👀 定义后端服务器池
upstream backend {
# 轮询(默认)
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}
# 👀 使用后端服务器池
server {
listen 80;
server_name myapp.example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
4. 负载均衡算法配置
# 👀 加权轮询:能者多劳
upstream backend_weighted {
server 192.168.1.10:8080 weight=5; # 干5份活
server 192.168.1.11:8080 weight=3; # 干3份活
server 192.168.1.12:8080 weight=2; # 干2份活
}
# 👀 最少连接:谁空闲找谁
upstream backend_least {
least_conn;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
# 👀 IP 哈希:固定用户找固定服务器
upstream backend_ip_hash {
ip_hash;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
# 👀 备份服务器
upstream backend_with_backup {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080 backup; # 备用服务器
}
5. 静态资源服务
# 👀 静态资源服务配置
server {
listen 80;
server_name static.example.com;
# 根目录
root /var/www/static;
# 默认首页
index index.html;
# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d; # 缓存30天
add_header Cache-Control "public, no-transform";
}
# HTML 不缓存
location ~* \.html$ {
expires -1;
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
}
}
6. 动静分离配置
# 👀 动静分离配置
server {
listen 80;
server_name myapp.example.com;
# 静态资源(由 Nginx 直接处理)
location /static/ {
alias /var/www/static/;
expires 7d;
add_header Cache-Control "public";
}
# 图片资源
location ~* \.(jpg|jpeg|png|gif|webp|svg)$ {
alias /var/www/images/;
expires 30d;
}
# CSS/JS 资源
location ~* \.(css|js)$ {
alias /var/www/static/css/;
expires 1d;
add_header Cache-Control "public";
}
# API 请求(转发给后端)
location /api/ {
proxy_pass http://backend_api;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# HTML 页面(后端渲染)
location / {
proxy_pass http://backend_render;
proxy_set_header Host $host;
}
}
7. location 匹配规则
什么是 location?
location 就像餐厅的"工作分工表",不同的客人(请求 URL)由不同的员工(处理方式)负责。
# 👀 精确匹配
location = / {
# 只匹配 / 这一个 URL
}
# 👀 前缀匹配(优先)
location / {
# 匹配所有以 / 开头的 URL
}
# 👀 正则匹配(按顺序,第一个匹配的生效)
location ~ \.php$ {
# 匹配以 .php 结尾的 URL
}
# 👀 不区分大小写的正则匹配
location ~* \.(jpg|png|gif)$ {
# 匹配图片文件
}
# 👀 ^~ 优先前缀匹配(匹配后不检查正则)
location ^~ /static/ {
# 匹配以 /static/ 开头的 URL
}
匹配优先级:
1. = 精确匹配(最高)
2. ^~ 前缀匹配
3. ~ 或 ~* 正则匹配(按顺序)
4. 前缀匹配(最低)
8. Rewrite 规则
# 👀 简单重定向
location /old {
return 301 /new;
}
# 👀 正则重写 URL
location /products {
rewrite ^/products/([0-9]+)$ /product?id=$1 break;
proxy_pass http://backend;
}
# 👀 去掉末尾斜杠
rewrite ^/(.*)/$ /$1 permanent;
# 👀 HTTP 跳转到 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
常用功能
1. 限流功能
为什么要限流?
想象一下:餐厅搞促销,来了一大批人,如果不限制人数,餐厅会被挤爆!
Nginx 的限流就是"控制入场人数"。
# 👀 限制请求速率
http {
# 定义限流区域
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
server {
listen 80;
# 使用限流规则
location / {
# 允许突发 20 个请求
limit_req zone=mylimit burst=20 nodelay;
proxy_pass http://backend;
}
}
}
限流类型:
| 类型 | 通俗解释 | 配置 |
|---|---|---|
| 请求速率限制 | 每秒最多处理多少请求 | limit_req |
| 连接数限制 | 同时最多多少连接 | limit_conn |
| 带宽限制 | 每秒最多传输多少数据 | limit_rate |
# 👀 连接数限制
limit_conn_zone $binary_remote_addr zone=connlimit:10m;
server {
limit_conn connlimit 10; # 每个 IP 最多 10 个连接
}
# 👀 带宽限制
location /download/ {
limit_rate 500k; # 限速 500KB/s
}
2. 访问控制
# 👀 允许/禁止 IP 访问
server {
# 允许特定 IP
location /admin/ {
allow 192.168.1.0/24; # 允许内网
allow 10.0.0.0/8;
deny all; # 禁止其他所有
}
# 禁止特定 IP
location / {
deny 192.168.1.100; # 禁止这个 IP
allow all; # 允许其他所有
}
}
3. HTTPS 配置
# 👀 HTTPS 服务器配置
server {
listen 443 ssl;
server_name example.com;
# SSL 证书
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
# SSL 配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
# 其他配置...
location / {
root /var/www/html;
index index.html;
}
}
4. 日志配置
# 👀 访问日志
server {
access_log /var/log/nginx/example.com.access.log main;
# 自定义日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
}
# 👀 条件日志(只记录慢请求)
map $request_time $loggable {
'~^[0-9.]+$' 0; # 慢请求不记录
default 1; # 正常请求记录
}
5. Gzip 压缩
什么是 Gzip?
就像搬家时把衣服压缩成真空袋,体积小了很多,传输更快。
# 👀 启用 Gzip 压缩
http {
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_comp_level 6;
server {
location / {
# 所有符合条件的响应都会自动压缩
}
}
}
性能优化
1. worker 进程优化
# 👀 自动设置 worker 进程数(推荐)
worker_processes auto;
# 👀 每个 worker 进程的最大连接数
events {
worker_connections 65535;
use epoll; # Linux 高效事件模型
multi_accept on; # 一次接受多个连接
}
2. Buffer 和超时设置
# 👀 Buffer 配置
http {
# 客户端请求体 buffer
client_body_buffer_size 10K;
# 客户端请求头 buffer
client_header_buffer_size 1k;
# 大请求体 buffer
large_client_header_buffers 4 8k;
# 代理 buffer
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
# 超时设置
client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 15;
send_timeout 10;
}
3. 缓存配置
# 👀 打开文件缓存
http {
open_file_cache max=10000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}
4. TCP 优化
# 👀 系统层面优化(需要 root)
# 在 /etc/sysctl.conf 中添加:
# net.core.somaxconn = 65535
# net.core.netdev_max_backlog = 65535
# net.ipv4.tcp_max_syn_backlog = 65535
http {
# Nginx 配置
sendfile on;
tcp_nopush on; # 等待数据包填满再发送
tcp_nodelay on; # 禁用 Nagle 算法
keepalive_requests 10000;
}
5. 静态资源优化
# 👀 静态资源缓存配置
server {
# 图片缓存 30 天
location ~* \.(jpg|jpeg|png|gif|ico|webp)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
# CSS/JS 缓存 7 天
location ~* \.(css|js)$ {
expires 7d;
add_header Cache-Control "public";
}
# 字体缓存 30 天
location ~* \.(woff|woff2|ttf|eot|otf)$ {
expires 30d;
add_header Cache-Control "public";
}
}
6. 安全优化
# 👀 安全响应头
server {
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 "no-referrer-when-downgrade" always;
}
# 👀 隐藏 Nginx 版本号
server_tokens off;
# 👀 限制请求方法
location / {
limit_except GET POST PUT DELETE {
deny all;
}
}
HTTPS 配置
1. 获取 SSL 证书
# 👀 使用 Let's Encrypt 免费证书
sudo apt install certbot python3-certbot-nginx
# 👀 获取证书
sudo certbot --nginx -d example.com -d www.example.com
# 👀 自动续期
sudo certbot renew --dry-run
2. HTTPS 完整配置
# 👀 HTTP 转 HTTPS
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$server_name$request_uri;
}
# 👀 HTTPS 服务器
server {
listen 443 ssl http2;
server_name example.com www.example.com;
# SSL 证书
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# SSL 配置(安全)
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 off;
# 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;
root /var/www/html;
index index.html;
}
3. HTTP/2 配置
# 👀 启用 HTTP/2
server {
listen 443 ssl http2;
# HTTP/2 自动协商,无需额外配置
}
日志分析
1. 日志格式详解
# 👀 定义详细日志格式
log_format detailed '$remote_addr - $remote_user [$time_local] '
'"$request" '
'$status $body_bytes_sent '
'"$http_referer" '
'"$http_user_agent" '
'$request_time '
'$upstream_response_time';
# 应用到 server
access_log /var/log/nginx/example.com.access.log detailed;
日志字段解释:
| 字段 | 通俗解释 | 示例 |
|---|---|---|
$remote_addr |
客户端 IP | 192.168.1.100 |
$remote_user |
认证用户名 | - |
$time_local |
请求时间 | 02/Jun/2025:10:30:00 +0800 |
$request |
请求行 | GET /index.html HTTP/1.1 |
$status |
HTTP 状态码 | 200, 404, 500 |
$body_bytes_sent |
发送字节数 | 1234 |
$http_referer |
来源页面 | https://google.com |
$http_user_agent |
浏览器信息 | Mozilla/5.0… |
$request_time |
请求处理时间(秒) | 0.123 |
$upstream_response_time |
后端响应时间 | 0.456 |
2. 日志分析命令
# 👀 查看访问最多的 IP
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -10
# 👀 查看访问最多的页面
awk '{print $7}' access.log | sort | uniq -c | sort -rn | head -10
# 👀 查看 HTTP 状态码统计
awk '{print $9}' access.log | sort | uniq -c | sort -rn
# 👀 查看慢请求(超过1秒)
awk '$NF > 1 {print $0}' access.log
# 👀 查看带宽使用
awk '{sum+=$10} END {print sum/1024/1024 " MB"}' access.log
# 👀 查看特定时间段日志
awk '$4 >= "[02/Jun/2025:10:00:00" && $4 <= "[02/Jun/2025:11:00:00"' access.log
# 👀 查看 404 请求
awk '$9 == 404 {print $7}' access.log | sort | uniq -c | sort -rn | head -10
# 👀 查看 500 错误
awk '$9 ~ /^5/ {print $0}' access.log
3. 日志切割
# 👀 使用 logrotate 切割日志
# 创建 /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily # 每天切割
missingok # 忽略错误
rotate 14 # 保留14天
compress # 压缩旧日志
delaycompress # 延迟压缩
notifempty # 空日志不切割
create 0640 www-data adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
常见问题排查
问题 1:Nginx 无法启动
现象: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
通俗解释: 就像你要开店,但发现门口已经有人占着了(端口被占用)。
排查步骤:
# 👀 查看 80 端口被谁占用
sudo lsof -i :80
# 输出:
# COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
# nginx 1234 root 6u IPv4 12345 0t0 TCP *:http (LISTEN)
# nginx 1235 www 6u IPv4 12345 0t0 TCP *:http (LISTEN)
# 👀 查看 Nginx 状态
sudo systemctl status nginx
# 👀 测试配置文件语法
sudo nginx -t
# 输出:
# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful
解决方案:
- 如果端口被占用
# 杀掉占用进程
sudo kill $(lsof -t -i:80)
# 或者
sudo fuser -k 80/tcp
- 如果配置文件有错误
# 查看详细错误
sudo nginx -t -v
问题 2:502 Bad Gateway
现象: 访问网站提示 502 Bad Gateway
通俗解释: 前台( Nginx )找不到后厨(后端服务器),客人点的菜没人做。
排查步骤:
# 👀 查看 Nginx 错误日志
sudo tail -50 /var/log/nginx/error.log
# 👀 检查后端服务是否运行
curl http://127.0.0.1:8080/health
# 👀 检查上游服务器配置
sudo cat /etc/nginx/conf.d/upstream.conf
解决方案:
- 后端服务未启动
# 启动后端服务
sudo systemctl start your_backend_service
# 检查状态
sudo systemctl status your_backend_service
- 后端服务端口配置错误
# 检查 proxy_pass 配置
location / {
proxy_pass http://127.0.0.1:8080; # 确认端口正确
}
- 后端服务崩溃
# 查看后端日志
sudo journalctl -u your_backend_service -n 50
问题 3:504 Gateway Timeout
现象: 访问网站提示 504 Gateway Timeout
通俗解释: 前台等后厨做菜等太久,客人等不及走了。
排查步骤:
# 👀 检查 Nginx 超时配置
sudo cat /etc/nginx/conf.d/default.conf | grep -E "timeout|proxy_read"
# 👀 查看慢请求日志
sudo tail -100 /var/log/nginx/access.log | awk '$NF > 30 {print}'
解决方案:
# 👀 增加超时时间
location / {
proxy_pass http://backend;
# 超时设置
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 90s;
# 缓冲区设置
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
}
问题 4:403 Forbidden
现象: 访问网站提示 403 Forbidden
通俗解释: 前台不让你进,说你没权限。
排查步骤:
# 👀 查看 Nginx 错误日志
sudo tail -50 /var/log/nginx/error.log
# 👀 检查文件权限
ls -la /var/www/html/
# 👀 检查 Nginx 配置
sudo cat /etc/nginx/sites-enabled/default | grep -E "deny|allow|root"
解决方案:
- 文件权限问题
# 修改文件权限
sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html
- Nginx 权限问题
# 在 nginx.conf 中设置
user www-data;
worker_processes auto;
- SELinux 问题(CentOS)
# 临时关闭 SELinux
sudo setenforce 0
# 或者设置 SELinux 允许 Nginx 访问
sudo setsebool -P httpd_can_network_connect 1
问题 5:静态资源不加载
现象: 页面显示但 CSS/JS/图片不显示
通俗解释: 菜单(HTML)有了,但菜(静态资源)送不上桌。
排查步骤:
# 👀 查看浏览器控制台的错误
# 常见错误:Failed to load resource: net::ERR_CONNECTION_REFUSED
# 👀 检查静态文件路径
curl -I http://localhost/static/style.css
# 👀 查看 Nginx 错误日志
sudo tail -50 /var/log/nginx/error.log
解决方案:
# 👀 检查 root 路径配置
location /static/ {
alias /var/www/static/; # 确认路径正确
expires 7d;
}
# 👀 检查文件是否存在
ls -la /var/www/static/style.css
# 👀 如果是 MIME 类型问题
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
}
问题 6:负载不均匀
现象: 后端服务器负载差异很大
通俗解释: 领位员分配不均,有的厨师忙死,有的闲着。
排查步骤:
# 👀 查看后端服务器响应时间
tail -1000 /var/log/nginx/access.log | awk -F'"' '{print $NF}' | sort | uniq -c
# 👀 检查 Nginx upstream 配置
sudo cat /etc/nginx/conf.d/upstream.conf
解决方案:
# 👀 使用加权轮询
upstream backend {
server 192.168.1.10:8080 weight=3;
server 192.168.1.11:8080 weight=1;
}
# 👀 或使用最少连接算法
upstream backend {
least_conn;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
问题 7:Nginx 高负载
现象: 服务器 CPU/内存使用率高
通俗解释: 前台太忙了,处理不过来。
排查步骤:
# 👀 查看 Nginx 进程状态
sudo top -p $(pgrep nginx | tr '\n' ',')
# 👀 查看连接数
sudo ss -s
# 👀 查看 Nginx 连接状态
sudo nginx -V 2>&1 | grep -- "-T"
解决方案:
# 👀 优化 worker 进程
worker_processes auto;
worker_connections 65535;
# 👀 启用连接复用
keepalive_timeout 65;
keepalive_requests 10000;
# 👀 启用 gzip 压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript;
总结
核心概念
| 概念 | 通俗解释 |
|---|---|
| 正向代理 | 代理客户端,隐藏用户身份 |
| 反向代理 | 代理服务端,隐藏服务器身份 |
| 负载均衡 | 智能分配请求到多台服务器 |
| 动静分离 | 静态 Nginx 直接返回,动态转发后端 |
| Worker 进程 | 实际处理请求的"员工" |
配置要点
| 配置项 | 通俗解释 | 建议值 |
|---|---|---|
| worker_processes | 员工数量 | auto |
| worker_connections | 每个员工能接待多少人 | 65535 |
| keepalive_timeout | 保持连接时间 | 65 |
| gzip | 压缩传输 | on |
运维黄金法则
- 配置要验证 - 每次改配置先
nginx -t - 日志要分析 - 定期查看 access.log 和 error.log
- 超时要合理 - 太长等太久,太短容易超时
- 限流要配置 - 防止被刷爆
- 缓存要设置 - 提高响应速度
- 安全要重视 - HTTPS + 安全头
常用命令速查
| 操作 | 命令 |
|---|---|
| 启动 | sudo systemctl start nginx |
| 停止 | sudo systemctl stop nginx |
| 重启 | sudo systemctl restart nginx |
| 重载配置 | sudo nginx -s reload |
| 测试配置 | sudo nginx -t |
| 查看版本 | nginx -v |
| 查看状态 | sudo systemctl status nginx |
| 查看日志 | sudo tail -f /var/log/nginx/error.log |
日志字段速查
| 字段 | 含义 |
|---|---|
| $remote_addr | 客户端 IP |
| $status | HTTP 状态码 |
| $request_time | 请求处理时间 |
| $body_bytes_sent | 发送字节数 |
常见状态码
| 状态码 | 含义 | 通俗解释 |
|---|---|---|
| 200 | OK | 成功 |
| 301 | Moved Permanently | 永久重定向 |
| 302 | Found | 临时重定向 |
| 400 | Bad Request | 请求错误 |
| 401 | Unauthorized | 需要认证 |
| 403 | Forbidden | 没权限 |
| 404 | Not Found | 找不到 |
| 500 | Internal Server Error | 服务器出错 |
| 502 | Bad Gateway | 网关错误(后端挂了) |
| 503 | Service Unavailable | 服务不可用 |
| 504 | Gateway Timeout | 网关超时 |
最后一句话总结:
Nginx 就是"超级前台接待",用它做好反向代理、负载均衡、动静分离,配好缓存和限流,你的网站就能承受高并发、稳稳地跑!
持续更新中… 如有问题或建议,欢迎交流讨论!