💻 指令与配置

掌握Nginx核心指令和配置语法,是构建高性能Web服务的基础

核心指令

server

server { ... }

定义虚拟主机配置块,用于设置单个服务器的监听端口、域名等

示例:
server {
    listen 80;
    server_name example.com;
    ...
}

location

location [=|~|~*|^~] uri { ... }

匹配请求URI,定义特定路径的处理规则

示例:
location /api {
    proxy_pass http://backend;
}

proxy_pass

proxy_pass URL;

将请求代理到后端服务器

示例:
proxy_pass http://127.0.0.1:3000;

upstream

upstream name { ... }

定义后端服务器组,用于负载均衡

示例:
upstream backend {
    server 192.168.1.10:3000 weight=3;
    server 192.168.1.11:3000 weight=2;
    server 192.168.1.12:3000 backup;
    keepalive 32;
}

listen

listen address[:port] [options];

指定服务器监听的地址和端口

示例:
listen 80;
listen 443 ssl;

root

root path;

设置静态文件的根目录

示例:
root /var/www/html;

alias

alias path;

为location指定不同的文件系统路径

示例:
location /img {
    alias /var/images;
}

proxy_set_header

proxy_set_header field value;

设置代理请求头,传递客户端信息到后端

示例:
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

limit_req

limit_req zone=name burst=number [nodelay];

请求限流,防止DDoS攻击

示例:
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;

location /api {
    limit_req zone=api_limit burst=20 nodelay;
}

proxy_cache

proxy_cache zone | off;

启用代理缓存,提升响应速度

示例:
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;

ssl_certificate

ssl_certificate file;

指定SSL证书文件路径

示例:
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;

gzip

gzip on | off;

启用gzip压缩,减少传输数据量

示例:
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript;

常用变量

$scheme 请求协议(http/https)
$host 请求的主机名
$uri 请求的URI(不含参数)
$request_uri 完整的请求URI(含参数)
$remote_addr 客户端IP地址
$http_user_agent 客户端User-Agent
$request_method 请求方法(GET/POST等)
$request_time 请求处理时间
$upstream_addr 后端服务器地址
$upstream_status 后端状态码
$upstream_response_time 后端响应时间
$upstream_cache_status 缓存状态

查看更多指令,请参考 Nginx官方文档