SorryToPerson logo
返回
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:全局指令,如 userworker_processes
  • events:工作进程之间连接模型。
  • http:HTTP 服务配置。
  • server:虚拟主机配置。
  • location:URI 匹配与处理规则。

2. include 机制

  • 通过 include 分离配置,便于维护。
nginx
http {
  include /etc/nginx/conf.d/*.conf;
  include /etc/nginx/sites-enabled/*;
}
  • 常用配置拆分:mime.typesupstreamsslserver

3. 主要配置块说明

  • http:定义全局 HTTP 参数,如 sendfilekeepalive_timeout
  • server:定义一个监听入口,例如 listenserver_name
  • location:按 URI 匹配请求,如 =^~~~*

4. location 匹配优先级

  1. 精确匹配 =
  2. 前缀匹配 ^~
  3. 普通前缀匹配。
  4. 正则匹配 ~ / ~*,按先后顺序。
  5. 默认匹配 /

5. 常用模块功能

  • proxy_pass:反向代理。
  • fastcgi_pass:PHP/CGI 代理。
  • rewrite:URL 重写。
  • gzip:启用压缩。
  • ssl_certificate:TLS 证书。

6. 配置调优建议

  • 使用 nginx -t 校验配置。
  • 通过 worker_processes auto; 根据 CPU 自动设置。
  • worker_connectionsworker_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. 版本差异与模块兼容

  • nginxnginx-plus 指令略有差异。
  • 某些模块需要编译进内核,例如 ngx_brotlingx_http_geoip_module
  • 生产环境中建议使用稳定版本或 LTS 发行版。
Nginx配置运维