mcpField
R
reverse-proxy

reverse-proxy

github.com/bagelhole云与 DevOps1.2k481 次安装23 周前更新
代码仓库

关于 reverse-proxy

reverse-proxy 是面向运维人员的反向代理配置技能,提供 nginx 和 Traefik 示例,用于将客户端流量路由到后端,并配置 TLS、限流和访问控制。

主要功能

  1. 01配置 nginx 与 Traefik 代理
  2. 02按路径路由至多个服务
  3. 03终止 TLS 并转发流量
  4. 04设置限流、访问控制及安全头
  5. 05配置压缩并排查代理故障

适用场景

  1. 01将公网域名流量转发到后端
  2. 02在单一域名下路由多个服务
  3. 03为管理页面限制访问并配置 TLS

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/bagelhole/devops-security-agent-skills --skill reverse-proxy

安装后在 Claude Code 中输入/reverse-proxy确认已加载。

详细介绍

反向代理

配置反向代理,以路由流量、终止 TLS、实施速率限制,并作为客户端与后端服务之间的网关。

适用场景

  • 将来自公共域名的流量路由到一个或多个后端服务。
  • 在边缘节点终止 TLS,并将普通 HTTP 转发到后端。
  • 添加速率限制、CORS、安全标头和访问控制。
  • 将多个服务整合到单个域名下,并根据路径进行路由。
  • 处理 WebSocket 升级、gRPC 代理或 HTTP/2 透传。

前置条件

  • 后端服务已运行,且主机和端口已知。
  • TLS 证书(Let's Encrypt、ACM,或用于开发的自签名证书)。
  • 已安装 nginx 1.25+ 或 Traefik 3.x。
  • DNS 记录已指向代理服务器。

nginx 反向代理

基本 HTTPS 代理并重定向
# /etc/nginx/sites-available/app.example.com
server {
    listen 80;
    server_name app.example.com;
    return 301 https://$host$request_uri;
}

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

    # TLS configuration
    ssl_certificate     /etc/letsencrypt/live/app.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers on;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;

    # Security headers
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
    add_header X-Frame-Options DENY always;
    add_header X-Content-Type-Options nosniff always;
    add_header Referrer-Policy strict-origin-when-cross-origin always;

    # Proxy to backend
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        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;

        # Timeouts
        proxy_connect_timeout 5s;
        proxy_read_timeout 60s;
        proxy_send_timeout 60s;

        # Buffering
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
    }
}
根据路径将请求路由到多个服务
server {
    listen 443 ssl http2;
    server_name app.example.com;

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

    # Frontend SPA
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
    }

    # API backend
    location /api/ {
        proxy_pass http://127.0.0.1:8080/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_read_timeout 120s;
    }

    # WebSocket endpoint
    location /ws/ {
        proxy_pass http://127.0.0.1:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_read_timeout 86400s;  # 24h for long-lived connections
    }

    # Static assets with caching
    location /static/ {
        alias /var/www/static/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}
速率限制
# Define rate limit zones in http block
http {
    # 10 requests/second per IP
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;

    # 1 request/second for login
    limit_req_zone $binary_remote_addr zone=login_limit:10m rate=1r/s;

    # Connection limit per IP
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
}

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

    # Apply rate limit to API
    location /api/ {
        limit_req zone=api_limit burst=20 nodelay;
        limit_req_status 429;
        proxy_pass http://127.0.0.1:8080;
    }

    # Strict rate limit on auth endpoints
    location /api/auth/ {
        limit_req zone=login_limit burst=5;
        limit_req_status 429;
        proxy_pass http://127.0.0.1:8080;
    }

    # Connection limit
    location / {
        limit_conn conn_limit 100;
        proxy_pass http://127.0.0.1:3000;
    }
}
Gzip 和 Brotli 压缩
http {
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;
    gzip_min_length 256;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 5;

    # Brotli (requires ngx_brotli module)
    # brotli on;
    # brotli_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;
    # brotli_comp_level 6;
}
使用 Certbot 配置 Let's Encrypt
# Install certbot with nginx plugin
sudo apt install certbot python3-certbot-nginx

# Obtain and install certificate
sudo certbot --nginx -d app.example.com -d www.example.com

# Auto-renewal is configured via systemd timer
sudo systemctl status certbot.timer

# Manual renewal test
sudo certbot renew --dry-run

Traefik 反向代理

静态配置
# traefik.yml
entryPoints:
  web:
    address: ":80"
    http:
      redirections:
        entryPoint:
          to: websecure
          scheme: https
  websecure:
    address: ":443"

certificatesResolvers:
  letsencrypt:
    acme:
      email: [email protected]
      storage: /letsencrypt/acme.json
      httpChallenge:
        entryPoint: web

providers:
  docker:
    exposedByDefault: false
  file:
    directory: /etc/traefik/dynamic/

api:
  dashboard: true
  insecure: false

log:
  level: INFO

accessLog:
  filePath: /var/log/traefik/access.log
动态配置(文件提供程序)
# /etc/traefik/dynamic/services.yml
http:
  routers:
    app:
      rule: "Host(`app.example.com`)"
      entryPoints:
        - websecure
      service: app
      tls:
        certResolver: letsencrypt
      middlewares:
        - security-headers
        - rate-limit

    api:
      rule: "Host(`app.example.com`) && PathPrefix(`/api`)"
      entryPoints:
        - websecure
      service: api
      tls:
        certResolver: letsencrypt

  services:
    app:
      loadBalancer:
        servers:
          - url: "http://127.0.0.1:3000"
        healthCheck:
          path: /health
          interval: 10s
          timeout: 3s

    api:
      loadBalancer:
        servers:
          - url: "http://127.0.0.1:8080"
        healthCheck:
          path: /api/health
          interval: 10s
          timeout: 3s

  middlewares:
    security-headers:
      headers:
        stsSeconds: 63072000
        stsIncludeSubdomains: true
        frameDeny: true
        contentTypeNosniff: true
        browserXssFilter: true
        referrerPolicy: strict-origin-when-cross-origin

    rate-limit:
      rateLimit:
        average: 100
        burst: 50
        period: 1m
使用 Docker 标签配置 Traefik
# docker-compose.yml
version: "3.8"

services:
  traefik:
    image: traefik:v3.0
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ./traefik.yml:/etc/traefik/traefik.yml:ro
      - letsencrypt:/letsencrypt

  frontend:
    image: my-frontend:latest
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.frontend.rule=Host(`app.example.com`)"
      - "traefik.http.routers.frontend.tls.certresolver=letsencrypt"
      - "traefik.http.services.frontend.loadbalancer.server.port=3000"

  api:
    image: my-api:latest
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.api.rule=Host(`app.example.com`) && PathPrefix(`/api`)"
      - "traefik.http.routers.api.tls.certresolver=letsencrypt"
      - "traefik.http.services.api.loadbalancer.server.port=8080"
      - "traefik.http.routers.api.middlewares=api-ratelimit"
      - "traefik.http.middlewares.api-ratelimit.ratelimit.average=50"
      - "traefik.http.middlewares.api-ratelimit.ratelimit.burst=25"

volumes:
  letsencrypt:

nginx 测试和管理

# Test configuration syntax
sudo nginx -t

# Reload without downtime
sudo nginx -s reload

# View active connections
sudo nginx -s status

# Check which config file is active
nginx -V 2>&1 | grep -o '\-\-conf-path=[^ ]*'

# Monitor access logs
tail -f /var/log/nginx/access.log

# Monitor error logs
tail -f /var/log/nginx/error.log

IP 允许列表和地理位置屏蔽

# Allow only specific IPs (admin panel)
location /admin/ {
    allow 203.0.113.0/24;
    allow 198.51.100.5;
    deny all;
    proxy_pass http://127.0.0.1:3000;
}

# Block by country (requires GeoIP2 module)
# geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
#     auto_reload 60m;
#     $geoip2_data_country_iso_code country iso_code;
# }
# if ($geoip2_data_country_iso_code = "XX") {
#     return 403;
# }

故障排查

症状原因解决方法
502 Bad Gateway后端未运行或无法访问确认后端正在监听;检查 proxy_pass URL
504 Gateway Timeout后端响应过慢增大 proxy_read_timeout;检查后端性能
混合内容警告未设置 X-Forwarded-Proto添加 proxy_set_header X-Forwarded-Proto $scheme
WebSocket 在 60 秒后断开默认代理超时已过期为 WebSocket 位置设置 proxy_read_timeout 86400s
速率限制误伤正常用户区域速率限制过严增大 rate 或 burst 值;为不同端点使用不同区域
Let's Encrypt 续期失败端口 80 被阻止或服务器块配置错误确保 .well-known/acme-challenge/ 可访问
Traefik 对所有路由都返回 404未检测到 Docker 标签确认已挂载 Docker 套接字;检查 exposedByDefault 设置
TLS 握手失败证书链不完整在 ssl_certificate 中包含中间证书

相关技能

评论

支持 Markdown