欢迎光临
我们一直在努力

Nginx 配置文件详解

Nginx 配置文件详解

Nginx 是一款高性能的 Web 服务器、反向代理服务器、负载均衡器和静态资源服务器。
理解 Nginx 配置文件,是做网站部署、反向代理、HTTPS、负载均衡和运维排错的基础。


一、Nginx 配置文件在哪里?

不同系统安装方式略有不同。

1. 常见主配置文件路径

系统 / 安装方式主配置文件
Ubuntu / Debian /etc/nginx/nginx.conf
CentOS / RHEL /etc/nginx/nginx.conf
源码安装 /usr/local/nginx/conf/nginx.conf
Docker 官方镜像 /etc/nginx/nginx.conf

2. 常见站点配置目录

Ubuntu / Debian 常见结构:

/etc/nginx/
├── nginx.conf
├── conf.d/
├── sites-available/
├── sites-enabled/
├── modules-enabled/

CentOS / RHEL 常见结构:

/etc/nginx/
├── nginx.conf
├── conf.d/
└── default.d/

Docker 官方镜像常见结构:

/etc/nginx/
├── nginx.conf
├── conf.d/
│ └── default.conf


二、Nginx 配置文件整体结构

Nginx 配置由多个上下文组成:

# 全局配置区

events {
# 事件配置区
}

http {
# HTTP 配置区

server {
# 虚拟主机配置区

location / {
# 路由匹配配置区
}
}
}

整体层级:

main 全局块
├── events 事件块
└── http HTTP 块
├── upstream 上游服务块
└── server 虚拟主机块
└── location 路由匹配块


三、全局配置 main

全局配置写在最外层,影响 Nginx 整体运行。

示例:

user nginx;
worker_processes auto;
pid /run/nginx.pid;
error_log /var/log/nginx/error.log warn;


1. user

指定 Nginx worker 进程运行用户。

user nginx;

或:

user www-data;

常见用户:

系统常见用户
Ubuntu/Debian www-data
CentOS/RHEL nginx
源码安装 nobody 或自定义用户

作用:

  • 控制 Nginx 访问文件权限
  • 提升安全性
  • 避免 worker 进程以 root 运行

注意:
master 进程通常仍由 root 启动,用于绑定 80/443 端口;worker 进程会切换到指定用户。


2. worker_processes

指定 worker 进程数量。

worker_processes auto;

推荐使用:

worker_processes auto;

表示根据 CPU 核心数自动设置。

也可以手动设置:

worker_processes 4;


3. pid

指定 Nginx 进程 ID 文件。

pid /run/nginx.pid;


4. error_log

指定错误日志路径和级别。

error_log /var/log/nginx/error.log warn;

日志级别从低到高:

debug < info < notice < warn < error < crit < alert < emerg

常用:

error_log /var/log/nginx/error.log warn;

排错时可临时改为:

error_log /var/log/nginx/error.log debug;


四、events 事件块

events 用于配置连接处理模型。

示例:

events {
worker_connections 1024;
use epoll;
multi_accept on;
}


1. worker_connections

每个 worker 进程最大连接数。

worker_connections 1024;

理论最大连接数:

worker_processes × worker_connections

例如:

4 × 1024 = 4096

注意:
实际还受系统文件描述符限制影响。


2. use epoll

Linux 下推荐使用 epoll:

use epoll;

通常 Nginx 会自动选择,一般可以不写。


3. multi_accept

允许 worker 一次接受多个新连接。

multi_accept on;

高并发场景可以开启。


五、http 块

http 块是 Nginx Web 服务核心区域。

常见配置:

http {
include /etc/nginx/mime.types;
default_type application/octet-stream;

sendfile on;
keepalive_timeout 65;

gzip on;

access_log /var/log/nginx/access.log;

include /etc/nginx/conf.d/*.conf;
}


1. include

引入其他配置文件。

include /etc/nginx/mime.types;
include /etc/nginx/conf.d/*.conf;

好处:

  • 配置模块化
  • 多站点分离
  • 便于维护

2. mime.types

定义文件扩展名和 MIME 类型关系。

include /etc/nginx/mime.types;

例如:

.html -> text/html
.css -> text/css
.js -> application/javascript
.png -> image/png

如果 MIME 类型不正确,浏览器可能无法正常解析 CSS/JS。


3. default_type

默认响应类型。

default_type application/octet-stream;


4. sendfile

是否启用高效文件传输。

sendfile on;

建议开启,适合静态文件服务。


5. keepalive_timeout

HTTP 长连接超时时间。

keepalive_timeout 65;

表示客户端连接保持 65 秒。


6. client_max_body_size

限制客户端上传文件大小。

client_max_body_size 50m;

如果上传文件超过限制,可能报:

413 Request Entity Too Large


7. gzip

启用压缩。

gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
gzip_min_length 1k;

作用:

  • 减少传输体积
  • 提高页面加载速度
  • 降低带宽消耗

六、server 块

server 表示一个虚拟主机。

示例:

server {
listen 80;
server_name example.com www.example.com;

root /var/www/html;
index index.html index.htm;

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


1. listen

监听端口。

listen 80;
listen 443 ssl;

常见:

端口用途
80 HTTP
443 HTTPS
8080 测试服务
8000/9000 后端服务代理

监听 IPv6:

listen [::]:80;


2. server_name

配置域名。

server_name example.com www.example.com;

也可以使用通配符:

server_name *.example.com;

默认服务器:

listen 80 default_server;


3. root

指定网站根目录。

root /var/www/html;

访问:

http://example.com/index.html

实际读取:

/var/www/html/index.html


4. index

默认首页文件。

index index.html index.htm index.php;


七、location 块

location 用于匹配 URL 路径。

示例:

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


1. location 匹配类型

写法含义
location / 普通前缀匹配
location = /login 精确匹配
location ^~ /static/ 优先前缀匹配
location ~ \\.php$ 正则匹配,区分大小写
`location ~* .(jpg png)$`

匹配优先级大致为:

= 精确匹配
^~ 优先前缀匹配
~ / ~* 正则匹配
普通前缀匹配


2. try_files

按顺序尝试文件是否存在。

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

常用于静态网站。

前端 SPA 应用常用:

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

适用于:

  • Vue
  • React
  • Angular
  • Vite
  • Nuxt 静态部署

3. alias 与 root 区别

root 示例

location /static/ {
root /var/www;
}

访问:

/static/a.png

实际路径:

/var/www/static/a.png

alias 示例

location /static/ {
alias /data/static/;
}

访问:

/static/a.png

实际路径:

/data/static/a.png

区别:

root = 根目录 + URI
alias = 用指定目录替换 location 路径

注意:
alias 目录路径通常要以 / 结尾。


八、反向代理配置

Nginx 最常用功能之一是反向代理。

示例:

server {
listen 80;
server_name api.example.com;

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

访问:

http://api.example.com

实际转发到:

http://127.0.0.1:3000


1. 常用代理头

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

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;
}

含义:

配置说明
Host 原始域名
X-Real-IP 客户端真实 IP
X-Forwarded-For 代理链路 IP
X-Forwarded-Proto 原始协议 http/https

2. proxy_pass 路径规则

情况 1:不带 /

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

请求:

/api/user

转发为:

http://127.0.0.1:3000/api/user


情况 2:带 /

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

请求:

/api/user

转发为:

http://127.0.0.1:3000/user

这个区别非常重要。


九、负载均衡 upstream

upstream 用于配置后端服务池。

示例:

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 app.example.com;

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


1. 默认轮询

upstream backend {
server app1:8080;
server app2:8080;
}

请求会轮流分发。


2. 权重 weight

upstream backend {
server app1:8080 weight=3;
server app2:8080 weight=1;
}

app1 接收更多流量。


3. ip_hash

upstream backend {
ip_hash;
server app1:8080;
server app2:8080;
}

同一客户端 IP 尽量分配到同一后端。

适用于:

  • 简单会话保持
  • 老系统 session 粘滞

4. least_conn

upstream backend {
least_conn;
server app1:8080;
server app2:8080;
}

请求转发到当前连接数较少的服务器。


十、HTTPS SSL 配置

HTTPS 示例:

server {
listen 443 ssl http2;
server_name example.com;

ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;

location / {
root /var/www/html;
index index.html;
}
}

HTTP 跳转 HTTPS:

server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}


常用 SSL 优化配置

ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;


十一、日志配置

1. 访问日志

access_log /var/log/nginx/access.log;


2. 错误日志

error_log /var/log/nginx/error.log warn;


3. 自定义日志格式

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;


十二、静态资源缓存

location ~* \\.(jpg|jpeg|png|gif|css|js|ico|svg|woff|woff2)$ {
expires 30d;
add_header Cache-Control "public";
}

作用:

  • 提升访问速度
  • 减少服务器压力
  • 降低带宽消耗

十三、防盗链配置

location ~* \\.(jpg|jpeg|png|gif)$ {
valid_referers none blocked example.com *.example.com;
if ($invalid_referer) {
return 403;
}
}


十四、访问控制

1. IP 白名单 / 黑名单

location /admin/ {
allow 192.168.1.0/24;
deny all;
}


2. Basic Auth 基础认证

location /admin/ {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}

生成密码文件:

sudo apt install apache2-utils
htpasswd -c /etc/nginx/.htpasswd admin


十五、限流配置

1. limit_req 请求频率限制

在 http 块定义:

limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;

在 server 或 location 中使用:

location /api/ {
limit_req zone=req_limit burst=20 nodelay;
proxy_pass http://backend;
}

含义:

参数说明
rate=10r/s 每秒 10 个请求
burst=20 突发队列 20 个
nodelay 不延迟处理突发请求

2. limit_conn 连接数限制

limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

server {
location / {
limit_conn conn_limit 20;
}
}


十六、常见完整配置示例

1. 静态网站配置

server {
listen 80;
server_name example.com;

root /var/www/html;
index index.html;

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

location ~* \\.(jpg|png|css|js|ico|svg)$ {
expires 30d;
add_header Cache-Control "public";
}
}


2. Vue / React 前端项目配置

server {
listen 80;
server_name frontend.example.com;

root /var/www/frontend/dist;
index index.html;

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


3. 后端 API 反向代理

server {
listen 80;
server_name api.example.com;

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

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;
}
}


4. 前后端分离配置

server {
listen 80;
server_name app.example.com;

root /var/www/app/dist;
index index.html;

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

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

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;
}
}

注意:

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

这里 proxy_pass 后面带 /,会去掉 /api/ 前缀。


5. HTTPS + 反向代理

server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}

server {
listen 443 ssl http2;
server_name example.com;

ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;

ssl_protocols TLSv1.2 TLSv1.3;

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

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 配置后,不要直接重启,先检查语法。

1. 检查配置语法

sudo nginx -t

成功示例:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful


2. 平滑重载配置

sudo systemctl reload nginx

或:

sudo nginx -s reload


3. 重启 Nginx

sudo systemctl restart nginx


4. 查看状态

sudo systemctl status nginx


十八、常见错误排查

1. 端口被占用

错误:

bind() to 0.0.0.0:80 failed

查看端口:

sudo ss -tulnp | grep :80


2. 403 Forbidden

常见原因:

  • 文件权限不足
  • 目录没有执行权限
  • 没有 index 文件
  • root 路径错误
  • SELinux 限制

排查:

ls -ld /var/www/html
ls -l /var/www/html


3. 404 Not Found

常见原因:

  • root 路径写错
  • location 匹配错误
  • try_files 配置错误
  • 文件不存在

4. 502 Bad Gateway

常见原因:

  • 后端服务没启动
  • proxy_pass 地址错误
  • 后端端口不通
  • Unix socket 权限问题

排查:

systemctl status backend
ss -tulnp | grep 3000
curl http://127.0.0.1:3000
tail -f /var/log/nginx/error.log


5. 413 Request Entity Too Large

上传文件过大。

解决:

client_max_body_size 100m;


6. 配置不生效

排查:

nginx -t
systemctl reload nginx
nginx -T

nginx -T 可以输出完整最终配置。


十九、Nginx 配置最佳实践

1. 配置模块化

推荐:

include /etc/nginx/conf.d/*.conf;

每个站点一个配置文件:

/etc/nginx/conf.d/example.com.conf


2. 修改配置先测试

nginx -t

再 reload:

systemctl reload nginx


3. 不要滥用 if

Nginx 中 if 使用不当容易造成异常行为。
能用 try_files、return、map 的场景,尽量不用复杂 if。


4. 正确记录真实 IP

如果 Nginx 前面还有负载均衡,需要配置真实 IP:

set_real_ip_from 192.168.1.0/24;
real_ip_header X-Forwarded-For;


5. 合理设置日志轮转

日志长期不清理会占满磁盘。
Linux 通常使用 logrotate 管理 Nginx 日志。


6. 静态资源开启缓存和 gzip

gzip on;
expires 30d;


7. HTTPS 使用 TLS 1.2+

ssl_protocols TLSv1.2 TLSv1.3;


二十、Nginx 常用命令速查

# 查看版本
nginx -v

# 查看编译参数
nginx -V

# 检查配置
sudo nginx -t

# 输出完整配置
sudo nginx -T

# 启动服务
sudo systemctl start nginx

# 停止服务
sudo systemctl stop nginx

# 重启服务
sudo systemctl restart nginx

# 平滑重载
sudo systemctl reload nginx

# 查看状态
sudo systemctl status nginx

# 查看错误日志
tail -f /var/log/nginx/error.log

# 查看访问日志
tail -f /var/log/nginx/access.log


总结

Nginx 配置文件的核心结构是:

main
├── events
└── http
├── upstream
└── server
└── location

最常用配置包括:

  • worker_processes
  • worker_connections
  • server
  • listen
  • server_name
  • root
  • index
  • location
  • try_files
  • proxy_pass
  • upstream
  • ssl_certificate
  • access_log
  • error_log

如果你掌握了:

静态网站部署
反向代理
HTTPS 配置
负载均衡
日志排查
配置测试与重载

就已经具备了 Nginx 日常运维和项目部署的核心能力。

赞(0)
未经允许不得转载:171主机测评 » Nginx 配置文件详解
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址