Nginx2026-04-15·8 分钟
Nginx 配置结构与常用模块
介绍 Nginx 配置文件层级、常见块、执行顺序与模块使用规范。
Nginx 配置结构与常用模块
1. Nginx 配置文件层级
nginx.conf 常见结构:
nginx
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
server {
listen 80;
server_name example.com;
location / {
root /usr/share/nginx/html;
index index.html;
}
}
}main:全局指令,如user、worker_processes。events:工作进程之间连接模型。http:HTTP 服务配置。server:虚拟主机配置。location:URI 匹配与处理规则。
2. include 机制
- 通过
include分离配置,便于维护。
nginx
http {
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}- 常用配置拆分:
mime.types、upstream、ssl、server。
3. 主要配置块说明
http:定义全局 HTTP 参数,如sendfile、keepalive_timeout。server:定义一个监听入口,例如listen、server_name。location:按 URI 匹配请求,如=、^~、~、~*。
4. location 匹配优先级
- 精确匹配
=。 - 前缀匹配
^~。 - 普通前缀匹配。
- 正则匹配
~/~*,按先后顺序。 - 默认匹配
/。
5. 常用模块功能
proxy_pass:反向代理。fastcgi_pass:PHP/CGI 代理。rewrite:URL 重写。gzip:启用压缩。ssl_certificate:TLS 证书。
6. 配置调优建议
- 使用
nginx -t校验配置。 - 通过
worker_processes auto;根据 CPU 自动设置。 worker_connections和worker_rlimit_nofile影响并发连接能力。
7. 示例:静态文件与反向代理共存
nginx
server {
listen 80;
server_name example.com;
location /static/ {
root /var/www;
}
location /api/ {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}8. 版本差异与模块兼容
nginx与nginx-plus指令略有差异。- 某些模块需要编译进内核,例如
ngx_brotli、ngx_http_geoip_module。 - 生产环境中建议使用稳定版本或 LTS 发行版。
Nginx配置运维