Nginx Web服务器

精选 Nginx 高性能 Web 服务器配置与反向代理备忘单,涵盖虚拟主机、SSL证书、反向代理、负载均衡及安全头配置示例。

#🚀 入门指引

#📦 安装与服务管理

  • Ubuntu / Debian 安装
    $ sudo apt update && sudo apt install -y nginx
    
  • RHEL / CentOS 安装
    $ sudo yum install -y epel-release nginx && sudo systemctl enable --now nginx
    
  • 服务控制命令
    $ sudo systemctl status nginx    # 查看状态
    $ sudo systemctl reload nginx    # 平滑重载配置
    $ sudo systemctl restart nginx   # 重启服务
    $ sudo nginx -t                  # 检查配置文件语法
    $ nginx -V                       # 查看版本及编译模块
    

#📁 核心路径指南

  • /etc/nginx/nginx.conf (主配置文件)
  • /etc/nginx/conf.d/*.conf (自定义子配置文件目录)
  • /etc/nginx/sites-available/ + sites-enabled/ (Debian/Ubuntu 站点配置模式)
  • /var/www/html (默认 Web 根目录)
  • 日志路径: /var/log/nginx/access.log, /var/log/nginx/error.log

#💡 最简 HTTP 服务示例

# /etc/nginx/conf.d/example.conf
server {
  listen 80;
  server_name example.com;
  root /var/www/example/public;

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

#⚙️ 配置结构

#🧩 核心配置块 (Blocks)

  • main (全局配置)
  • events (工作进程连接数)
  • httpserverlocation
  • stream (TCP/UDP 流量转发)
  • upstream (后端负载均衡池)
user  www-data;
worker_processes auto;

events { worker_connections 1024; }

http {
  include       mime.types;
  default_type  application/octet-stream;
  sendfile      on;
  keepalive_timeout 65;

  # 此处引入 server 虚拟主机配置...
}

#🎯 匹配优先级 (Location Match Order)

  • location 匹配顺序规则
    1. 精确匹配 =
    2. 优先前缀 ^~ (匹配后不再检查正则)
    3. 正则匹配 ~ / ~* (按出现的先后顺序)
    4. 普通前缀 (按最长路径匹配)
  • try_files 按指定顺序依次评估回退。
location = /healthz { return 204; }
location ^~ /static/ { expires 7d; }
location ~* \.(png|jpg|css|js)$ { expires 7d; }
location / { try_files $uri $uri/ /index.html; }

#📌 常用配置文件引入

http {
  include /etc/nginx/conf.d/*.conf;
  include /etc/nginx/snippets/*.conf; # Ubuntu/Debian 剪辑配置
}

#🌐 虚拟主机与重定向

#🏠 基础 Server 配置

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

#🔄 HTTP 强制跳转 HTTPS

server {
  listen 80;
  server_name example.com www.example.com;
  return 301 https://example.com$request_uri;
}

#🔀 规范域名重定向 (Non-WWW)

# 强制带 www 跳转不带 www 域名
server {
  listen 80;
  server_name www.example.com;
  return 301 $scheme://example.com$request_uri;
}

#🔒 TLS/SSL 安全配置

#🛡️ 基础 HTTPS 站点配置

server {
  listen 443 ssl http2;
  server_name example.com;

  ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

  ssl_protocols TLSv1.2 TLSv1.3;
  ssl_prefer_server_ciphers off;

  root /var/www/example/public;
}

#🔐 HSTS 与安全响应头

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;

#📜 免费证书 Let’s Encrypt (Certbot)

$ sudo apt install -y certbot python3-certbot-nginx
$ sudo certbot --nginx -d example.com -d www.example.com
$ sudo systemctl list-timers | grep certbot   # 检查证书自动续期定时任务

#🔀 反向代理 (Reverse Proxy)

#代理应用服务

upstream app {
  server 127.0.0.1:3000;
  # server unix:/run/app.sock; # 套接字模式
}

server {
  listen 80;
  server_name api.example.com;

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

#⚡ WebSockets 与长连接支持

location /socket.io/ {
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
  proxy_pass http://app;
}

#⏱️ 代理超时与缓冲区优化

proxy_connect_timeout 5s;
proxy_send_timeout    60s;
proxy_read_timeout    60s;
proxy_buffering       on;
proxy_buffers 16 16k;
proxy_busy_buffers_size 24k;

#⚡ 静态资源、压缩与缓存

#📁 静态资源优化

location /assets/ {
  alias /var/www/example/assets/;
  access_log off;
  expires 7d;
  add_header Cache-Control "public, max-age=604800, immutable";
}

#🗜️ Gzip 文本压缩

gzip on;
gzip_types text/plain text/css application/javascript application/json image/svg+xml;
gzip_min_length 1024;
gzip_comp_level 5;

#🚀 Brotli 压缩 (如已编译模块)

brotli on;
brotli_comp_level 5;
brotli_types text/plain text/css application/javascript application/json image/svg+xml;

#💾 代理缓存与微缓存

#缓存区 Zone 定义

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=micro:10m max_size=1g inactive=10m use_temp_path=off;
map $request_method $no_cache { default 0; POST 1; PUT 1; PATCH 1; DELETE 1; }

#应用代理缓存

location /api/ {
  proxy_cache micro;
  proxy_cache_bypass $no_cache;
  proxy_no_cache $no_cache;
  proxy_cache_valid 200 301 302 10s;
  proxy_cache_valid any 1s;
  add_header X-Cache-Status $upstream_cache_status;
  proxy_pass http://app;
}

#条件跳过缓存

# 登录用户跳过缓存(Cookie 示例)
map $http_cookie $logged_in {
  default 0;
  ~*"(session|auth|logged_in)" 1;
}
proxy_cache_bypass $logged_in;
proxy_no_cache $logged_in;

#🐘 PHP‑FPM / FastCGI 集成

#基础 PHP 处理器配置

location ~ \.php$ {
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
  fastcgi_param DOCUMENT_ROOT $realpath_root;
  fastcgi_pass unix:/run/php/php8.2-fpm.sock;
  fastcgi_buffers 16 16k;
  fastcgi_read_timeout 60s;
}

#单入口路由 (Front Controller)

location / {
  try_files $uri $uri/ /index.php?$args;
}

#安全阻断敏感文件

location ~* \.(?:ini|log|sh|sql|bak)$ { deny all; }
location ~ /\.(?!well-known) { deny all; }

#🔀 重写与单页应用 (SPA)

#try_files 通用匹配

location / {
  try_files $uri $uri/ /index.html;
}

#正则重写 (Rewrites)

# 移除末尾斜杠 (根目录除外)
if ($request_uri ~* "^(.+)/+$") { return 301 $1; }

# 废弃路径永久重定向到新路径
rewrite ^/old/(.*)$ /new/$1 permanent;

#单页应用 SPA (History 模式)

location / {
  try_files $uri /index.html;
}

#🛡️ 限流与防 CC / DoS 攻击

#请求速率限制

# 单 IP 限制 10 次/秒,突发允许 20 次
limit_req_zone $binary_remote_addr zone=reqs:10m rate=10r/s;

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

#并发连接数限制

limit_conn_zone $binary_remote_addr zone=conns:10m;
server {
  location /download/ {
    limit_conn conns 10;
  }
}

#请求体大小与超时

client_max_body_size 25m;
client_body_timeout 30s;
keepalive_timeout 65s;

#🔒 安全头与访问控制

#隐藏服务器版本号

server_tokens off;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;

#IP 白名单与黑名单

location /admin/ {
  allow 192.168.0.0/16;
  deny all;
}

#跨域资源共享 CORS 配置

location /api/ {
  add_header Access-Control-Allow-Origin "https://app.example.com" always;
  add_header Access-Control-Allow-Credentials "true" always;
  if ($request_method = OPTIONS) {
    add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
    add_header Access-Control-Allow-Headers "Authorization, Content-Type";
    return 204;
  }
  proxy_pass http://app;
}

#📊 日志与调试

#自定义日志格式

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for" '
                '$request_time $upstream_response_time';

access_log /var/log/nginx/access.log main;
error_log  /var/log/nginx/error.log warn;

#禁用特定路径日志

location /healthz { access_log off; }

#调试命令

$ sudo nginx -t                        # 校验语法
$ sudo nginx -s reload                 # 重载服务
$ tail -f /var/log/nginx/error.log     # 实时查看错误日志

#⚖️ 负载均衡 (Upstreams)

#负载均衡策略

策略指令 调度算法含义
(默认) 轮询 (Round-robin)
least_conn 最少连接数优先
ip_hash 根据客户端 IP 绑定会话
hash key 自定义 Key 哈希绑定

#后端服务池配置

upstream api_backends {
  least_conn;
  server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
  server 10.0.0.12:8080 max_fails=3 fail_timeout=30s;
  # server backup.example:8080 backup; # 备用节点
}

#故障转移策略

proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 3;

#💡 Nginx 常用内置变量

#请求与客户端变量

变量名称 含义描述
$host 请求头中的 Host / 服务名
$server_name 当前匹配的 server_name
$remote_addr 客户端真实 IP
$http_user_agent 客户端 User-Agent 字符串
$request_method HTTP 请求方法 (GET/POST...)

#路径与文件变量

变量名称 含义描述
$document_root 当前根目录路径
$realpath_root 规范化后的真实根目录路径
$request_uri 原始请求 URI (含参数)
$uri 规范化后的 URI (不含参数)
$args 原始 URL 查询参数

#Upstream 后端变量

变量名称 含义描述
$upstream_addr 实际处理请求的后端 Server 地址
$upstream_status 后端返回的响应状态码
$upstream_response_time 后端响应所消耗的耗时时间

#🔌 四层代理 (Stream TCP/UDP)

#TCP 端口代理

stream {
  upstream db {
    server 10.0.0.10:5432;
    server 10.0.0.11:5432;
  }
  server {
    listen 5432;
    proxy_pass db;
  }
}

#UDP 代理

stream {
  server {
    listen 53 udp;
    proxy_responses 1;
    proxy_timeout 2s;
    proxy_pass 1.1.1.1:53;
  }
}

#四层访问控制

stream {
  server {
    listen 6379;
    allow 10.0.0.0/8;
    deny all;
    proxy_pass 127.0.0.1:6379;
  }
}

#🧩 剪辑复用配置 (Snippets)

#安全头剪辑模块

# /etc/nginx/snippets/security.conf
server_tokens off;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;

#PHP 处理剪辑模块

# /etc/nginx/snippets/fastcgi-php.conf
location ~ \.php$ {
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
  fastcgi_param DOCUMENT_ROOT $realpath_root;
  fastcgi_pass unix:/run/php/php8.2-fpm.sock;
}

#代理头剪辑模块

# /etc/nginx/snippets/proxy-headers.conf
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;