Skip to content

配置语法

Nginx 配置由指令和块组成。

nginx
directive value;

block {
    directive value;
}

指令以分号结尾,块使用 {} 包裹。常见块包括 eventshttpserverlocationupstream

基本结构

nginx
user www-data;
worker_processes auto;

events {
    worker_connections 1024;
}

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

    sendfile on;
    keepalive_timeout 65;

    server {
        listen 80;
        server_name example.com;

        location / {
            root /var/www/example.com;
            index index.html;
            try_files $uri $uri/ =404;
        }
    }
}

全局块

全局块在最外层,影响 Nginx 进程自身。

nginx
user www-data;
worker_processes auto;
pid /run/nginx.pid;

常见指令:

  • user:worker 进程运行用户。
  • worker_processes:worker 进程数量,常用 auto
  • pid:主进程 PID 文件路径。

events

events 定义连接处理相关配置。

nginx
events {
    worker_connections 1024;
}

常见指令:

  • worker_connections:每个 worker 可同时处理的连接数。

http

http 定义 HTTP 服务的全局配置。

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

    sendfile on;
    gzip on;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

常见指令:

  • include:引入其他配置文件。
  • default_type:默认响应类型。
  • sendfile:启用高效文件传输。
  • gzip:启用 gzip 压缩。
  • access_log:访问日志。
  • error_log:错误日志。

server

server 定义虚拟主机,主要根据端口和域名选择。

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

详细匹配规则见 server 匹配

location

location 定义路径处理规则。

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

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

详细匹配规则见 location 匹配

upstream

upstream 定义上游服务组,常用于反向代理和负载均衡。

nginx
upstream backend {
    server 127.0.0.1:3000;
    server 127.0.0.1:3001;
}

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

配置检查

修改配置后先检查:

bash
nginx -t

确认无误后 reload:

bash
systemctl reload nginx

基于 MIT 许可发布