Nginx 进阶配置
HTTPS 配置
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/ssl/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# HSTS
add_header Strict-Transport-Security "max-age=63072000" always;
}
# HTTP 自动跳转 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
限流
请求频率限制
# http 块
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
server {
location /api/ {
limit_req zone=req_limit burst=20 nodelay;
proxy_pass http://backend;
}
}
| 参数 |
说明 |
| rate=10r/s |
每秒 10 个请求 |
| burst=20 |
突发流量允许 20 个排队 |
| nodelay |
不延迟,超过 burst 直接拒绝 |
并发连接限制
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
location /download/ {
limit_conn conn_limit 5; # 每 IP 最多 5 个并发
}
}
Location 匹配规则
| 符号 |
说明 |
优先级 |
| = |
精确匹配 |
最高 |
| ^~ |
前缀匹配,不检查正则 |
次高 |
| ~ |
区分大小写正则 |
第三 |
| ~* |
不区分大小写正则 |
第三 |
| / |
通用前缀 |
最低 |
location = / { return 200 "home"; }
location ^~ /static/ { root /var/www; }
location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; }
location / { try_files $uri /index.html; }
Rewrite 重写
# 旧路径跳转新路径(301 永久重定向)
rewrite ^/old-blog/(.*)$ /blog/$1 permanent;
# 伪静态
rewrite ^/article/(\d+)\.html$ /article.php?id=$1 last;
# if 条件判断
set $maintenance 0;
if (-f /var/www/maintenance.enable) {
set $maintenance 1;
}
if ($maintenance = 1) {
return 503;
error_page 503 /maintenance.html;
}
Nginx 缓存
# http 块
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:100m max_size=1g inactive=60m;
server {
location /api/ {
proxy_cache my_cache;
proxy_cache_valid 200 10m;
proxy_cache_valid 404 1m;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_pass http://backend;
}
}
日志配置
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" $request_time';
access_log /var/log/nginx/access.log main buffer=32k flush=5s;
error_log /var/log/nginx/error.log warn;
}