Nginx 配置速查手册:核心语法与实战案例

30 阅读1分钟

Nginx 配置速查手册:核心语法与实战案例

当你需要在几分钟内快速配置 Nginx 时,本文就是你的速查手册。每个知识点控制在 3 行以内,核心语法与常用示例一目了然。

核心语法速查

基础配置

语法说明示例
user设置运行 Nginx 的用户和组user nobody;
worker_processes设置工作进程数worker_processes 4;
error_log指定错误日志文件位置error_log /var/log/nginx/error.log warn;
pid指定 Nginx 进程 ID 文件位置pid /var/run/nginx.pid;

事件模块

语法说明示例
events事件处理块events {
worker_connections 1024;
}
worker_connections每个工作进程的最大连接数worker_connections 1024;

HTTP 核心模块

语法说明示例
httpHTTP 块,包含多个上下文http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
gzip on;
}
include包含其他配置文件include /etc/nginx/mime.types;
default_type设置默认的 MIME 类型default_type application/octet-stream;
sendfile使用 sendfile 优化文件传输sendfile on;
keepalive_timeout设置长连接的超时时间keepalive_timeout 65;
gzip开启或关闭 Gzip 压缩gzip on;

服务器块

语法说明示例
server定义一个虚拟主机server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html index.htm;
}
listen监听的端口或 IPlisten 80;
server_name虚拟主机的域名server_name example.com;
root站点根目录root /var/www/html;
index默认索引文件index index.html index.htm;

位置块

语法说明示例
location匹配 URL 并定义处理方式location / {
try_files $uri $uri/ =404;
}
try_files尝试按顺序查找文件,如果都未找到则返回最后一个参数指定的状态码或 URLtry_files $uri $uri/ =404;

反向代理

语法说明示例
proxy_pass将请求转发到后端服务器location /api {
proxy_pass http://backend_server;
}
proxy_set_header设置转发请求头proxy_set_header Host $host;

重定向

语法说明示例
return直接返回一个状态码或 URLlocation /old {
return 301 http://example.com/new;
}
rewriteURL 重写rewrite ^/old/([a-z]+)$ /new/$1 permanent;

负载均衡

语法说明示例
upstream定义后端服务器池upstream backend {
server backend1.example.com;
server backend2.example.com;
}
least_conn最少连接数调度upstream backend {
least_conn;
server backend1.example.com;
server backend2.example.com;
}
ip_hash基于客户端 IP 调度upstream backend {
ip_hash;
server backend1.example.com;
server backend2.example.com;
}

缓存

语法说明示例
proxy_cache_path定义缓存路径和配置proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;
proxy_cache启用缓存proxy_cache my_cache;
proxy_cache_key定义缓存键proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid设置缓存有效期proxy_cache_valid 200 301 302 10m;

安全

语法说明示例
limit_req限制请求速率limit_req zone=one burst=5 nodelay;
limit_conn限制连接数limit_conn addr 10;
ssl启用 SSLserver {
listen 443 ssl;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
}
add_header添加 HTTP 响应头add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";

日志

语法说明示例
access_log指定访问日志文件位置access_log /var/log/nginx/access.log combined;
log_format定义日志格式log_format combined '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

限制与优化

语法说明示例
client_max_body_size限制客户端请求的最大体大小client_max_body_size 10m;
server_tokens隐藏服务器版本信息server_tokens off;
tcp_nodelay禁用 Nagle 算法,减少延迟tcp_nodelay on;

常用示例

静态文件服务

server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }
}

反向代理

server {
    listen 80;
    server_name example.com;

    location /api {
        proxy_pass http://backend_server;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

重定向

server {
    listen 80;
    server_name example.com;

    location /old {
        return 301 http://example.com/new;
    }

    location /old2 {
        rewrite ^/old2/([a-z]+)$ /new/$1 permanent;
    }
}

负载均衡

upstream backend {
    least_conn;
    server backend1.example.com;
    server backend2.example.com;
}

server {
    listen 80;
    server_name example.com;

    location /api {
        proxy_pass http://backend;
        proxy_set_header Host $host;
    }
}

缓存

http {
    proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;

    server {
        listen 80;
        server_name example.com;

        location /api {
            proxy_cache my_cache;
            proxy_cache_key "$scheme$request_method$host$request_uri";
            proxy_cache_valid 200 301 302 10m;
            proxy_pass http://backend;
        }
    }
}

SSL 配置

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/priv哥key.pem;

    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
    }
}

安全配置

server {
    listen 80;
    server_name example.com;

    location /api {
        limit_req zone=one burst=5 nodelay;
        limit_conn addr 10;
        proxy_pass http://backend;
        proxy_set_header Host $host;
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";
    }
}

日志配置

http {
    log_format custom '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';

    server {
        listen 80;
        server_name example.com;

        access_log /var/log/nginx/access.log custom;
    }
}

性能优化

http {
    sendfile on;
    tcp_nodelay on;
    client_max_body_size 10m;
    server_tokens off;

    server {
        listen 80;
        server_name example.com;

        location / {
            root /var/www/html;
            index index.html index.htm;
        }
    }
}

进阶技巧

热备份与恢复

http {
    upstream backend {
        server backend1.example.com;
        server backend2.example.com backup;
    }

    server {
        listen 80;
        server_name example.com;

        location /api {
            proxy_pass http://backend;
            proxy_set_header Host $host;
        }
    }
}

动态内容缓存

http {
    proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;

    server {
        listen 80;
        server_name example.com;

        location /api {
            proxy_cache my_cache;
            proxy_cache_key "$scheme$request_method$host$request_uri";
            proxy_cache_valid 200 301 302 10m;
            proxy_pass http://backend;
            add_header X-Proxy-Cache $upstream_cache_status;
        }
    }
}

跨域资源共享 (CORS)

server {
    listen 80;
    server_name example.com;

    location /api {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        proxy_pass http://backend;
    }
}

压缩配置

http {
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_vary on;

    server {
        listen 80;
        server_name example.com;

        location / {
            root /var/www/html;
            index index.html index.htm;
        }
    }
}

防止 DDoS 攻击

http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

    server {
        listen 80;
        server_name example.com;

        location / {
            limit_req zone=one burst=5 nodelay;
            root /var/www/html;
            index index.html index.htm;
        }
    }
}

限制文件类型上传

server {
    listen 80;
    server_name example.com;

    location /upload {
        root /var/www/html;
        valid_referers none blocked example.com;
        if ($invalid_referer) {
            return 403;
        }

        if ($request_method = POST) {
            limit_except GET {
                allow 192.168.1.0/24;
                deny all;
            }
        }

        client_max_body_size 10m;
    }
}

动态服务器配置

http {
    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }

    server {
        listen 80;
        server_name example.com;

        location /ws {
            proxy_pass http://backend;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
        }
    }
}

限制 IP 访问

server {
    listen 80;
    server_name example.com;

    allow 192.168.1.0/24;
    deny all;

    location / {
        root /var/www/html;
        index index.html index.htm;
    }
}

限制请求方法

server {
    listen 80;
    server_name example.com;

    if ($request_method !~ ^(GET|POST)$) {
        return 405;
    }

    location / {
        root /var/www/html;
        index index.html index.htm;
    }
}

标准化错误页面

server {
    listen 80;
    server_name example.com;

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;

    location = /404.html {
        internal;
        root /var/www/html;
    }

    location = /50x.html {
        internal;
        root /var/www/html;
    }
}

日志切割

# 使用 logrotate 切割日志
# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 nginx adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
}

在线工具推荐

配置 Nginx 时,遇到复杂的 cron 表达式、正则表达式或 JSON 数据,可以使用 Hey Cron 进行快速生成和验证。Hey Cron 提供了多种实用工具,包括:

  • Cron 表达式生成器:中文描述秒转 cron 表达式
  • 正则表达式生成器:帮助你快速生成正则表达式
  • 中英互译:支持中文和英文的互译
  • JSON 格式化:帮助你格式化和验证 JSON 数据
  • Base64 编码解码:快速编码和解码 Base64 字符串
  • 时间戳转换:方便地在时间戳和日期时间之间进行转换
  • JWT 解析:帮助你解析 JWT 令牌

希望这些工具能提升你的开发效率,少走弯路。