1. Web技术基础与Nginx核心优势
1.1 Web服务架构解析
现代Web服务本质上是一个基于HTTP/HTTPS协议的客户端-服务器通信模型。当你在浏览器地址栏输入一个网址时,背后发生了以下关键交互流程:
- DNS解析:浏览器首先将域名(如www.example.com)解析为服务器IP地址
- TCP连接:与服务器建立TCP三次握手连接(HTTP默认端口80,HTTPS默认443)
- 请求发送:浏览器构造HTTP请求报文并发送
- 服务处理:服务器接收请求,处理业务逻辑并生成响应
- 内容返回:服务器返回HTML/CSS/JS等资源
- 渲染展示:浏览器解析响应内容并渲染页面
在这个过程中,Web服务器作为整个架构的入口网关,承担着请求分发、负载均衡、安全防护等重要职责。常见的Web服务器软件包括:
- Nginx:采用事件驱动的异步非阻塞架构,特别适合高并发场景
- Apache:传统的多进程/多线程模型,模块化设计功能全面
- IIS:微软开发的Windows平台专属Web服务器
1.2 Nginx的架构优势
Nginx之所以能在Web服务器领域占据主导地位,主要得益于其独特的设计哲学:
事件驱动模型:与传统Apache的"一个连接一个进程/线程"模式不同,Nginx使用单线程+事件循环机制。当请求到达时,Nginx不会阻塞等待IO操作完成,而是继续处理其他请求。这种设计使得Nginx在C10K(单机万级并发连接)场景下依然能保持高性能。
内存效率:Nginx的进程模型非常节省内存。实测表明,在10,000个非活跃HTTP保持连接(keep-alive)状态下,Nginx仅消耗约2.5MB内存,而传统服务器可能消耗数百MB。
热部署能力:支持不停止服务的情况下更新配置、升级二进制文件。这对于需要7×24小时运行的线上服务至关重要。
模块化设计:核心功能保持精简,通过模块扩展各种能力。例如:
- http_gzip_module:实现响应内容压缩
- http_ssl_module:提供HTTPS支持
- http_rewrite_module:支持URL重写规则
提示:在生产环境中,Nginx通常作为反向代理服务器部署在应用前端,既能高效处理静态资源,又能将动态请求转发给后端应用服务器(如Tomcat、uWSGI等)。
2. Nginx环境部署实战
2.1 系统环境准备
在开始安装前,需要确保系统满足以下条件:
- 操作系统:推荐使用Linux发行版(CentOS 7+/Ubuntu 18.04+)
- 权限要求:需要root或sudo权限执行安装命令
- 网络配置:
- 确保服务器能访问外网以下载安装包
- 防火墙开放80/443端口(临时测试可关闭防火墙)
- 依赖工具:
bash复制# 基础工具安装 yum install -y wget tar gzip # CentOS/RHEL apt install -y wget tar gzip # Ubuntu/Debian
2.2 两种安装方式详解
方式一:包管理器安装(推荐新手)
CentOS/RHEL系统:
bash复制# 添加EPEL仓库(提供最新版Nginx)
yum install -y epel-release
# 安装Nginx
yum install -y nginx
# 启动服务并设置开机自启
systemctl start nginx
systemctl enable nginx
# 验证服务状态
systemctl status nginx
Ubuntu/Debian系统:
bash复制# 更新软件包索引
apt update
# 安装Nginx
apt install -y nginx
# 管理服务
systemctl start nginx
systemctl enable nginx
systemctl status nginx
安装后验证:
- 查看安装版本:
nginx -v - 检查服务端口:
netstat -tulnp | grep nginx - 浏览器访问服务器IP,应看到Nginx欢迎页
方式二:源码编译安装(适合定制需求)
步骤1:安装编译依赖
bash复制# CentOS/RHEL
yum install -y gcc make pcre-devel zlib-devel openssl-devel
# Ubuntu/Debian
apt install -y build-essential libpcre3 libpcre3-dev zlib1g-dev libssl-dev
步骤2:下载并解压源码包
bash复制wget https://nginx.org/download/nginx-1.24.0.tar.gz
tar -zxvf nginx-1.24.0.tar.gz
cd nginx-1.24.0
步骤3:配置编译选项
bash复制./configure \
--prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_gzip_static_module \
--with-http_realip_module \
--with-http_stub_status_module
常用编译参数说明:
--with-http_ssl_module:启用HTTPS支持--with-http_v2_module:支持HTTP/2协议--with-stream:启用TCP/UDP代理功能--add-module=/path/to/module:添加第三方模块
步骤4:编译与安装
bash复制make -j$(nproc) # 并行编译,加快速度
make install
步骤5:创建系统服务
bash复制cat > /etc/systemd/system/nginx.service << 'EOF'
[Unit]
Description=nginx - high performance web server
Documentation=https://nginx.org/en/docs/
After=network.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
# 重新加载systemd配置
systemctl daemon-reload
两种安装方式对比:
| 特性 | 包管理器安装 | 源码编译安装 |
|---|---|---|
| 安装难度 | 简单(一键安装) | 复杂(需手动编译) |
| 版本 | 较旧(依赖仓库版本) | 最新(可自由选择版本) |
| 定制能力 | 有限 | 高度可定制 |
| 维护成本 | 低(自动更新) | 高(需手动升级) |
| 适合场景 | 生产环境快速部署 | 需要特定功能/性能调优 |
3. Nginx核心配置解析
3.1 配置文件结构
Nginx采用模块化的配置架构,主要配置文件通常位于:
code复制/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 推荐存放站点配置
│ └── example.conf # 具体站点配置
├── sites-available/ # 可用站点配置(Ubuntu风格)
├── sites-enabled/ # 启用的站点链接(Ubuntu风格)
├── modules/ # 动态模块目录
├── mime.types # 文件类型映射
└── logs/ # 日志目录
nginx.conf 核心结构:
nginx复制# 全局块:影响Nginx整体运行的配置
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
# events块:影响网络连接配置
events {
worker_connections 1024;
use epoll; # Linux高效事件模型
}
# http块:网站服务相关配置
http {
include mime.types;
default_type application/octet-stream;
# 日志格式定义
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;
# 其他HTTP相关配置...
include /etc/nginx/conf.d/*.conf; # 包含子配置文件
}
3.2 静态网站配置实例
创建/etc/nginx/conf.d/static_site.conf:
nginx复制server {
listen 80;
server_name example.com www.example.com;
# 网站根目录设置
root /var/www/static_site;
index index.html;
# 日志配置
access_log /var/log/nginx/static_site_access.log;
error_log /var/log/nginx/static_site_error.log;
# 静态资源缓存优化
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
}
# 自定义错误页面
error_page 404 /404.html;
location = /404.html {
internal;
}
}
关键配置说明:
listen:指定监听端口,可配置为listen 80 default_server表示默认站点server_name:支持通配符(*.example.com)和正则表达式root:必须确保Nginx进程用户(通常为nginx或www-data)有读取权限location:URI匹配规则,优先级顺序:精确匹配(=) > 正则匹配(~) > 前缀匹配
3.3 反向代理配置实战
场景:将Nginx作为前端,反向代理到后端Java应用(Spring Boot)
配置示例:
nginx复制server {
listen 80;
server_name api.example.com;
# 全局代理设置
proxy_http_version 1.1;
proxy_set_header Connection "";
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;
# 静态资源直接由Nginx处理
location /static/ {
root /var/www/api;
expires 7d;
}
# API请求转发到后端
location /api/ {
proxy_pass http://127.0.0.1:8080/; # 注意结尾的/会去除/api前缀
# 超时设置
proxy_connect_timeout 60s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
}
# WebSocket支持
location /ws/ {
proxy_pass http://127.0.0.1:8080/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
负载均衡配置:
nginx复制upstream backend_servers {
server 192.168.1.101:8080 weight=3; # 权重3
server 192.168.1.102:8080;
server 192.168.1.103:8080 backup; # 备用服务器
# 负载均衡策略
least_conn; # 最少连接算法
# ip_hash; # 会话保持
}
server {
location / {
proxy_pass http://backend_servers;
}
}
4. 高级配置与性能优化
4.1 HTTPS安全配置
使用Let's Encrypt免费证书:
bash复制# 安装certbot工具
apt install -y certbot python3-certbot-nginx # Ubuntu
yum install -y certbot python3-certbot-nginx # CentOS
# 获取证书(需域名已解析)
certbot --nginx -d example.com -d www.example.com
# 自动续期设置
(crontab -l 2>/dev/null; echo "0 0 1 * * certbot renew --quiet") | crontab -
手动配置SSL优化:
nginx复制server {
listen 443 ssl http2; # 启用HTTP/2
server_name example.com;
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_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...';
# 会话复用减少TLS握手开销
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_session_tickets off;
# HSTS安全头
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
# 其他安全头
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options SAMEORIGIN;
add_header X-XSS-Protection "1; mode=block";
# 其余配置...
}
4.2 性能调优参数
全局优化:
nginx复制# nginx.conf的全局块
worker_processes auto; # 自动匹配CPU核心数
worker_rlimit_nofile 65535; # 每个worker能打开的文件描述符数量
events {
worker_connections 8192; # 每个worker的最大连接数
multi_accept on; # 一次接受所有新连接
use epoll; # Linux高效事件模型
}
http {
# 文件传输优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# 连接超时设置
keepalive_timeout 65;
keepalive_requests 1000;
# 响应缓冲
client_body_buffer_size 16k;
client_max_body_size 8m; # 最大上传文件大小
# Gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript;
gzip_min_length 1024;
gzip_comp_level 6;
}
静态资源优化:
nginx复制location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff2)$ {
expires 365d;
add_header Cache-Control "public, immutable";
# 开启Brotli压缩(需安装对应模块)
brotli_static on;
gzip_static on;
}
5. 运维监控与故障排查
5.1 日志分析技巧
日志格式定制:
nginx复制log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'rt=$request_time uct="$upstream_connect_time" '
'uht="$upstream_header_time" urt="$upstream_response_time"';
常用日志分析命令:
bash复制# 实时监控访问日志
tail -f /var/log/nginx/access.log
# 统计HTTP状态码
awk '{print $9}' access.log | sort | uniq -c | sort -rn
# 找出请求时间最长的URL
awk '{print $7,$NF}' access.log | sort -k2 -rn | head -20
# 分析TOP IP
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -20
# 使用GoAccess生成可视化报告
goaccess /var/log/nginx/access.log --log-format=COMBINED
5.2 常见故障排查
问题1:Nginx启动失败
bash复制# 检查配置语法
nginx -t
# 查看错误日志
tail -n 50 /var/log/nginx/error.log
# 常见错误:
# - 端口被占用:netstat -tulnp | grep :80
# - 权限问题:ls -ld /var/www/ && ps aux | grep nginx
问题2:502 Bad Gateway
可能原因:
- 后端服务未启动或崩溃
- 代理配置错误(如错误的proxy_pass地址)
- 后端服务响应超时
检查方法:
bash复制# 检查后端服务状态
systemctl status your_backend_service
# 测试后端连通性
curl -v http://backend_server:port
# 调整代理超时设置
proxy_connect_timeout 60s;
proxy_read_timeout 300s;
问题3:413 Request Entity Too Large
解决方案:
nginx复制# 增加客户端请求体大小限制
client_max_body_size 20M;
问题4:CPU占用过高
排查步骤:
top查看进程资源占用strace -p <nginx_worker_pid>跟踪系统调用- 检查是否受到DDoS攻击(异常IP请求)
- 优化worker_processes和worker_connections配置
5.3 性能监控方案
Nginx状态模块:
nginx复制location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
访问输出示例:
code复制Active connections: 291
server accepts handled requests
16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 106
Prometheus监控:
- 安装nginx-prometheus-exporter
- 配置Nginx状态端点
- Grafana展示关键指标:
- 请求率(QPS)
- 连接数
- 响应时间分布
- 上游服务健康状态
6. 实际部署经验分享
6.1 多环境配置管理
推荐目录结构:
code复制/etc/nginx/
├── conf.d/
│ ├── common/ # 通用配置片段
│ │ ├── gzip.conf
│ │ ├── security.conf
│ ├── production/ # 生产环境配置
│ ├── staging/ # 预发布环境
│ ├── development/ # 开发环境
├── templates/ # 配置模板
└── sites-available/ # 按业务划分的配置
使用环境变量:
nginx复制# 在/etc/nginx/nginx.conf顶部
env DEPLOY_ENV;
# 在配置文件中条件判断
map $DEPLOY_ENV $log_level {
production warn;
staging info;
default debug;
}
error_log /var/log/nginx/error.log $log_level;
6.2 灰度发布方案
基于Cookie的灰度:
nginx复制# 灰度服务器组
upstream gray_backend {
server 192.168.1.105:8080;
}
# 生产服务器组
upstream prod_backend {
server 192.168.1.101:8080;
server 192.168.1.102:8080;
}
server {
location / {
# 检查灰度cookie
if ($http_cookie ~* "gray_release=true") {
proxy_pass http://gray_backend;
break;
}
proxy_pass http://prod_backend;
}
}
基于权重的流量切分:
nginx复制split_clients "${remote_addr}${http_user_agent}" $variant {
10% "gray";
90% "prod";
}
server {
location / {
if ($variant = "gray") {
proxy_pass http://gray_backend;
break;
}
proxy_pass http://prod_backend;
}
}
6.3 安全加固建议
-
隐藏Nginx版本信息:
nginx复制server_tokens off; -
限制HTTP方法:
nginx复制if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 405; } -
防止目录遍历:
nginx复制location ~* \.(php|asp|jsp)$ { deny all; } -
速率限制:
nginx复制limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s; location /api/ { limit_req zone=api_limit burst=20 nodelay; proxy_pass http://backend; } -
禁用不需要的模块:编译时移除不需要的模块减小攻击面
7. 典型应用场景实现
7.1 动静分离架构
nginx复制server {
listen 80;
server_name example.com;
# 动态请求转发到应用服务器
location ~ \.(php|jsp|do)$ {
proxy_pass http://app_server;
}
# 静态资源直接处理
location ~* \.(jpg|jpeg|png|gif|ico|css|js|html|txt)$ {
root /var/www/static;
expires 30d;
access_log off;
}
# 前端路由处理(单页应用)
location / {
try_files $uri $uri/ /index.html;
}
}
7.2 微服务API网关
nginx复制# 用户服务
upstream user_service {
server 192.168.1.201:8001;
}
# 订单服务
upstream order_service {
server 192.168.1.202:8002;
}
server {
listen 80;
server_name api.example.com;
# 统一API前缀
location /api/v1 {
# 跨域支持
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
# 路由分发
location /api/v1/users {
proxy_pass http://user_service;
}
location /api/v1/orders {
proxy_pass http://order_service;
}
# 全局熔断设置
proxy_next_upstream error timeout http_502 http_503;
proxy_connect_timeout 2s;
proxy_read_timeout 5s;
}
# 健康检查端点
location = /health {
access_log off;
return 200 "OK";
}
}
7.3 文件下载服务器
nginx复制server {
listen 80;
server_name download.example.com;
# 文件下载目录
root /data/downloads;
# 禁用目录列表
autoindex off;
# 文件下载设置
location / {
# 限制下载速度(100KB/s)
limit_rate 100k;
# 强制下载而非预览
if ($request_filename ~* ^.*?\.(txt|pdf|doc|xls|ppt|zip|rar)$) {
add_header Content-Disposition 'attachment';
}
# 大文件分片下载支持
slice 10m;
proxy_set_header Range $http_range;
proxy_set_header If-Range $http_if_range;
}
# 专用大文件下载路径
location /large-files/ {
internal; # 只允许内部重定向访问
alias /data/large-files/;
# 断点续传配置
aio on;
directio 10m;
output_buffers 4 128k;
}
}
8. 容器化部署方案
8.1 Docker基础部署
Dockerfile示例:
dockerfile复制FROM nginx:1.24-alpine
# 移除默认配置
RUN rm -rf /etc/nginx/conf.d/*
# 添加自定义配置
COPY nginx.conf /etc/nginx/nginx.conf
COPY conf.d/ /etc/nginx/conf.d/
# 添加静态资源
COPY static/ /var/www/html/
# 暴露端口
EXPOSE 80 443
# 启动命令
CMD ["nginx", "-g", "daemon off;"]
docker-compose.yml示例:
yaml复制version: '3'
services:
web:
image: custom-nginx
build: .
ports:
- "80:80"
- "443:443"
volumes:
- ./logs:/var/log/nginx
- ./conf.d:/etc/nginx/conf.d
restart: unless-stopped
8.2 Kubernetes Ingress配置
Ingress资源定义:
yaml复制apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$1
nginx.ingress.kubernetes.io/ssl-redirect: "true"
spec:
tls:
- hosts:
- example.com
secretName: example-tls
rules:
- host: example.com
http:
paths:
- path: /api/(.*)
pathType: Prefix
backend:
service:
name: api-service
port:
number: 8080
- path: /
pathType: Prefix
backend:
service:
name: web-service
port:
number: 80
性能优化参数:
yaml复制apiVersion: v1
kind: ConfigMap
metadata:
name: nginx-config
data:
worker-processes: "4"
keepalive-requests: "10000"
upstream-keepalive-connections: "200"
9. 性能测试与调优
9.1 基准测试方法
使用wrk进行压力测试:
bash复制# 基本测试(100个连接,持续30秒)
wrk -t4 -c100 -d30s http://example.com
# 带Lua脚本的复杂测试
wrk -t4 -c100 -d30s -s post.lua http://example.com/api
测试指标解读:
- Latency:响应时间分布(平均/最大/标准差)
- Requests/sec:每秒请求数(QPS)
- Transfer/sec:网络吞吐量
- 错误率:非200状态码比例
9.2 性能瓶颈分析
系统级检查:
bash复制# CPU使用率
top -p $(pgrep nginx | head -n1)
# 内存占用
pmap -x $(pgrep nginx | head -n1) | tail -n1
# 文件描述符
ls -l /proc/$(pgrep nginx | head -n1)/fd | wc -l
# 网络连接
ss -ant | grep :80 | wc -l
Nginx特定指标:
acceptsvshandled:如果差异大说明连接被丢弃Reading/Writing/Waiting:查看worker进程状态分布- 通过
stub_status模块监控活跃连接数
9.3 调优参数参考
系统内核参数:
bash复制# 增加最大文件描述符
echo "fs.file-max = 100000" >> /etc/sysctl.conf
# 优化TCP协议栈
echo "net.ipv4.tcp_tw_reuse = 1" >> /etc/sysctl.conf
echo "net.ipv4.tcp_max_tw_buckets = 20000" >> /etc/sysctl.conf
echo "net.core.somaxconn = 65535" >> /etc/sysctl.conf
# 生效配置
sysctl -p
Nginx关键参数:
nginx复制events {
worker_connections 16384; # 需与系统ulimit -n匹配
multi_accept on;
}
http {
# 缓冲池优化
proxy_buffers 16 32k;
proxy_buffer_size 64k;
# 临时文件优化
client_body_temp_path /dev/shm/nginx_temp 1 2;
proxy_temp_path /dev/shm/nginx_proxy;
fastcgi_temp_path /dev/shm/nginx_fastcgi;
# 开启reuseport(Linux 3.9+)
listen 80 reuseport;
}
10. 版本升级与迁移
10.1 平滑升级步骤
-
备份现有配置和网站数据
bash复制cp -r /etc/nginx /etc/nginx_backup tar -czvf /backup/nginx_data_$(date +%F).tar.gz /var/www -
下载新版本源码包
bash复制
wget https://nginx.org/download/nginx-1.25.3.tar.gz -
编译安装(保留旧配置)
bash复制
./configure --prefix=/usr/local/nginx \ --with-http_ssl_module \ --with-http_v2_module \ --with-http_realip_module \ --with-http_stub_status_module \ --with-http_gzip_static_module make -
执行升级(不停止服务)
bash复制mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.old cp objs/nginx /usr/local/nginx/sbin/nginx make upgrade -
验证新版本
bash复制
nginx -v nginx -t
10.2 配置迁移检查清单
-
语法变更检查:
- 移除废弃指令(如
ssl on在1.15.0后已废弃) - 更新新版本推荐语法
- 移除废弃指令(如
-
模块兼容性验证:
bash复制nginx -V # 查看编译参数和模块列表 -
性能基准测试:
- 使用相同测试参数对比QPS和延迟
- 监控内存占用变化
-
灰度发布策略:
- 先在小部分流量上升级验证
- 监控错误日志和系统指标
-
回滚方案准备:
bash复制# 快速回滚到旧版本 cp /usr/local/nginx/sbin/nginx.old /usr/local/nginx/sbin/nginx systemctl restart nginx
11. 扩展功能实现
11.1 地理围栏访问控制
nginx复制# 加载GeoIP模块(需预先安装)
load_module modules/ngx_http_geoip_module.so;
http {
# 加载IP地理数据库
geoip_country /usr/share/GeoIP/GeoIP.dat;
# 定义允许的国家代码
map $geoip_country_code $allowed_country {
default no;
CN yes;
US yes;
JP yes;
}
server {
# 根据国家限制访问
if ($allowed_country = no) {
return 403 "Access Denied";
}
}
}
11.2 实时日志分析
ELK方案配置:
-
安装Filebeat收集Nginx日志
yaml复制# filebeat.yml filebeat.inputs: - type: log paths: - /var/log/nginx/access.log json.keys_under_root: true -
Logstash解析日志
conf复制filter { grok { match => { "message" => "%{COMBINEDAPACHELOG}" } } geoip { source => "clientip" } } -
Kibana展示关键指标:
- 请求地理分布图
- 状态码饼图
- 流量时间序列
11.3 动态证书管理
使用acme.sh自动化:
bash复制# 安装acme.sh
curl https://get.acme.sh | sh
# 签发证书
acme.sh --issue -d example.com --nginx
# 安装证书
acme.sh --install-cert -d example.com \
--key-file /etc/nginx/ssl/example.com.key \
--fullchain-file /etc/nginx/ssl/example.com.crt \
--reloadcmd "systemctl reload nginx"
多域名通配符证书:
bash复制acme.sh --issue -d example.com -d '*.example.com' --dns dns_cf
12. 最佳实践总结
经过多年Nginx运维实践,我总结了以下关键经验:
-
配置管理原则:
- 每个站点/服务使用独立配置文件
- 公共配置片段通过include引入
- 版本控制所有配置文件变更
-
性能优化要点:
- 静态资源启用长期缓存和压缩
- 动态请求合理设置超时和重试策略
- 根据CPU核心数设置worker_processes
-
安全加固必须项:
- 禁用server_tokens隐藏版本
- 限制HTTP方法到必需的最小集
- 所有生产流量强制HTTPS
-
监控告警关键指标:
- 5xx错误率突增
- 请求延迟P99值
- worker进程内存增长
-
灾备恢复方案:
- 定期备份完整配置和证书
- 准备快速回滚脚本
- 文档记录所有自定义模块编译参数
在实际生产环境中,Nginx的稳定运行离不开细致的配置和持续的监控。建议每季度进行一次配置审计和性能测试,确保随着业务增长,Nginx配置也能持续优化。