Nginx 配置的核心在于理解其模块化架构和指令继承规则,掌握 location 匹配优先级、反向代理参数调优、静态资源缓存策略,就能解决 90% 以上的日常配置需求,下面从安装到安全加固,分层拆解每一个关键环节。
安装与基础管理
推荐使用发行版官方源或 Nginx 官方源安装,避免源码编译带来的依赖管理难题。
- CentOS/RHEL 系:
yum install nginx或dnf install nginx - Ubuntu/Debian 系:
apt install nginx - 安装后执行
systemctl enable --now nginx实现开机自启并立即运行
验证安装是否成功:访问服务器公网 IP,看到 Welcome to nginx! 页面即表示服务正常,若无法访问,优先检查云服务商安全组是否放行 80 端口。
配置文件结构与核心指令
Nginx 主配置文件位于 /etc/nginx/nginx.conf,其结构遵循分层嵌套逻辑:
- 全局块:配置 worker 进程数、日志路径、PID 文件
- events 块:配置连接处理机制,如
worker_connections - http 块:配置 HTTP 服务器通用属性,如 MIME 类型、默认日志格式
- server 块:虚拟主机配置,可包含多个 server 监听不同域名或端口
- location 块:URI 匹配规则与请求处理方式
核心配置示例:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;
index index.php index.html;
access_log /var/log/nginx/example.access.log;
error_log /var/log/nginx/example.error.log;
location / {
try_files $uri $uri/ =404;
}
location ~ .php$ {
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}

location 匹配规则精讲
这是 Nginx 配置中最容易出错、也最影响线上稳定性的部分,匹配优先级从高到低依次为:
location = /uri:精确匹配,完全相等才命中location ^~ /path/:普通前缀匹配,命中后不再检查正则location ~ pattern:区分大小写的正则匹配location ~ pattern:不区分大小写的正则匹配location /path/:普通前缀匹配,最长匹配优先
独立见解:很多教程将正则优先级放在前缀匹配之前,这在生产环境中容易导致误伤,建议将所有静态资源路径用 ^~ 明确隔离,正则只用于动态请求分流。
location ^~ /static/ {
alias /data/www/static/;
expires 30d;
access_log off;
}
location ~ .(php|jsp)$ {
# 动态请求处理
}
反向代理与负载均衡配置
反向代理是 Nginx 最常用的场景之一,核心参数需要重点关注:
upstream backend {
server 192.168.1.10:8080 weight=3;
server 192.168.1.11:8080 weight=1;
keepalive 32;
}
server {
listen 80;
server_name api.example.com;
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 5s;
proxy_read_timeout 30s;
proxy_send_timeout 30s;
}
}
关键参数解读:
proxy_set_header用于传递客户端真实 IP,后端应用依赖此字段获取用户来源- 超时时间需根据业务特性调整,API 接口建议
proxy_read_timeout设 30s keepalive配置与后端的长连接复用,能显著降低 TCP 握手开销
性能调优实践
1 静态资源缓存
location ~ .(jpg|jpeg|png|gif|ico|css|js)$ { expires 7d; add_header Cache-Control "public, max-age=604800"; access_log off; }
2 Gzip 压缩传输
gzip on;
gzip_min_length 1k;
gzip_comp_level 5;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss image/svg+xml;
gzip_vary on;
3 worker 进程优化
worker_processes auto;
worker_rlimit_nofile 65535;
events {
worker_connections 4096;
use epoll;
multi_accept on;
}
酷番云经验案例:我们曾在酷番云服务器上为一款电商小程序提供配置优化服务,客户使用 4 核 8G 配置,默认 worker_processes 为 1,峰值并发时 CPU 单核满载而其他核心闲置,调整为 worker_processes auto 后,吞吐量提升了约 3 倍,同时将 worker_connections 从 1024 提升到 4096,配合 use epoll,单机稳定支撑了 8000+ 并发连接,如果您的业务流量波动较大,建议在酷番云控制台搭配负载均衡产品使用,让 Nginx 专注处理请求转发,流量分发交给专业 LB 设备。
安全加固必备配置
1 隐藏 Nginx 版本号
server_tokens off;
2 禁止非 GET/POST 请求
if ($request_method !~ ^(GET|POST)$) {
return 405;
}
3 限制单 IP 并发与速率
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
server {
limit_conn conn_limit 20;
limit_req zone=req_limit burst=20 nodelay;
}
4 强制 HTTPS 跳转
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
常见问题排查思路
| 现象 | 排查方向 | 解决路径 |
|---|---|---|
| 502 Bad Gateway | 后端服务是否存活、FastCGI 是否启动 | systemctl status php-fpm 查看后端日志 |
| 404 静态资源丢失 | location 匹配规则错误或 root/alias 路径写错 | 执行 nginx -T 查看实际加载配置 |
| 403 Forbidden | 目录索引权限不足或 SELinux 未放行 | 检查目录权限,执行 setenforce 0 测试 |
| 高并发连接重置 | worker_connections 过小或文件描述符限制 | 调大参数并执行 ulimit -n 检查 |
避坑建议:修改配置后务必执行 nginx -t 测试语法,再执行 nginx -s reload 平滑重载,不要直接重启 Nginx,否则会中断当前所有活跃连接。
相关问答
问:Nginx 配置中 root 和 alias 的区别是什么?
答:root 会将完整 URI 拼接到 root 指定的路径后面,root /var/www/html,请求 /images/a.jpg 时,实际查找文件为 /var/www/html/images/a.jpg,而 alias 会将 location 匹配部分替换为指定路径,location /images/ { alias /data/pics/; },请求 /images/a.jpg 时,实际查找文件为 /data/pics/a.jpg。alias 常用于静态文件目录与 URL 路径不一致的场景,使用 alias 时路径末尾必须加 ,否则会报错。
问:Nginx 出现大量 TIME_WAIT 连接怎么办?
答:TIME_WAIT 是 TCP 四次挥手后的正常状态,但数量过多会消耗端口资源。最有效的解决方案是启用长连接复用,在 upstream 配置中添加 keepalive 32,并在 location 中设置:
proxy_http_version 1.1;
proxy_set_header Connection "";
同时可调整内核参数 net.ipv4.tcp_tw_reuse = 1 和 net.ipv4.tcp_fin_timeout = 30,允许复用 TIME_WAIT 状态的连接,需注意 tcp_tw_recycle 在 NAT 环境下不要开启,会引发连接异常。
图片来源于AI模型,如侵权请联系管理员。作者:酷小编,如若转载,请注明出处:https://www.kufanyun.com/ask/739983.html

