Nginx 配置文件详解
Nginx 的核心在于其模块化的配置结构。掌握配置文件的层级关系是高效运维的基础。
🏗️ 配置文件结构
典型的 nginx.conf 结构如下:
nginx
# 1. 全局块 (Global Context)
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
# 2. Events 块
events {
worker_connections 1024;
}
# 3. HTTP 块
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
# 4. Server 块 (虚拟主机)
server {
listen 80;
server_name example.com;
# 5. Location 块 (路由匹配)
location / {
root html;
index index.html index.htm;
}
}
}🔍 层级关系详解
- 全局块 (Global):配置影响 Nginx 全局的指令。如运行用户、Worker 进程数、日志路径等。
- Events 块:配置影响 Nginx 服务器与用户的网络连接。如
worker_connections(每个进程的最大连接数)。 - HTTP 块:配置最频繁的部分。包括代理、缓存、日志格式定义以及第三方模块的配置。
- Server 块:代表一个虚拟主机。可以配置多个 Server 块来支撑多个域名或端口。
- Location 块:基于 URL 路径进行匹配。这是配置反向代理、静态资源路由的核心。
⚡ 常用配置指令
1. 性能优化
worker_processes auto;:自动根据 CPU 核心数启动对应数量的工作进程。sendfile on;:开启高效文件传输模式,显著提升静态文件发送性能。gzip on;:开启 Gzip 压缩,减少网络传输流量。
2. 包含配置 (include)
为了避免 nginx.conf 过于臃肿,通常使用 include 将各站点的配置拆分:
nginx
http {
...
include /etc/nginx/conf.d/*.conf; # 加载该目录下所有以 .conf 结尾的文件
}3. 反向代理基础
nginx
location /api/ {
proxy_pass http://backend_server:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}🚦 配置匹配规则 (Location)
Nginx 匹配 URL 的优先级如下:
location = /path:精确匹配(最高优先级)。location ^~ /path:前缀优先匹配(匹配到后停止搜索正则)。location ~ pattern:正则匹配(区分大小写)。location ~* pattern:正则匹配(不区分大小写)。location /path:普通前缀匹配(最低优先级)。
