Skip to content

语法

配置文件结构

Nginx 的配置文件通常位于 /etc/nginx/nginx.conf,其基本结构如下:

nginx
# 全局块
user nginx;
worker_processes auto;

# 事件块
events {
    worker_connections 1024;
}

# HTTP 块
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;
        }
    }
}

HTTP 配置

常见指令

  • include: 引入其他配置文件。
    nginx
    include /etc/nginx/mime.types;
  • default_type: 设置默认 MIME 类型。
    nginx
    default_type application/octet-stream;
  • sendfile: 启用高效文件传输。
    nginx
    sendfile on;
  • keepalive_timeout: 设置客户端连接的超时时间。
    nginx
    keepalive_timeout 65;

Server 配置

常见指令

  • listen: 指定监听的端口。
    nginx
    listen 80;
  • server_name: 定义服务器名称。
    nginx
    server_name example.com;
  • error_page: 自定义错误页面。
    nginx
    error_page 404 /404.html;
  • access_logerror_log: 定义访问日志和错误日志路径。
    nginx
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

Location 配置

常见指令

  • root: 设置根目录。
    nginx
    location / {
        root /usr/share/nginx/html;
    }
  • index: 指定默认首页文件。
    nginx
    location / {
        index index.html;
    }
  • proxy_pass: 转发请求到后端服务器。
    nginx
    location /api/ {
        proxy_pass http://127.0.0.1:3000;
    }
  • rewrite: URL 重写。
    nginx
    location /old-path/ {
        rewrite ^/old-path/(.*)$ /new-path/$1 permanent;
    }
  • try_files: 尝试访问文件或返回指定内容。
    nginx
    location / {
        try_files $uri $uri/ =404;
    }

Upstream 配置

常见指令

  • upstream: 定义后端服务器组,用于负载均衡。
    nginx
    upstream backend {
        server 127.0.0.1:8080;
        server 127.0.0.1:8081;
    }
  • server 块中使用 proxy_pass 指向 upstream
    nginx
    server {
        listen 80;
        location / {
            proxy_pass http://backend;
        }
    }

基于 MIT 许可发布