Nginx 运维高频指令与常用配置片段。
基础指令
nginx -t # 测试配置
nginx -s reload # 平滑重载
nginx -s stop # 停止
sudo systemctl reload nginx # systemd 方式重载
sudo systemctl status nginx # 状态
gzip 压缩
gzip on;
gzip_types text/plain text/css application/javascript application/json image/svg+xml;
gzip_min_length 1024;
静态资源缓存
location ~* \.(js|css|png|jpg|svg|woff2)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
限流
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://127.0.0.1:8080;
}
访问控制
# 仅允许内网访问
location /admin/ {
allow 192.168.1.0/24;
deny all;
}
跳转
# HTTP -> HTTPS
server {
listen 80;
server_name blog.example.com;
return 301 https://$host$request_uri;
}
日志
sudo tail -f /var/log/nginx/access.log
sudo tail -f /var/log/nginx/error.log
自定义日志格式:
log_format main '$remote_addr - $request_time s "$request" $status $body_bytes_sent';
access_log /var/log/nginx/access.log main;
常见排查
curl -I http://localhost # 检查响应头
sudo nginx -t && sudo systemctl reload nginx # 改配置后的标准流程
ss -tlnp | grep :80 # 确认端口监听