# 默认服务器 - 拒绝直接IP访问 server { listen 80 default_server; listen [::]:80 default_server; server_name _; return 444; } # HTTP 重定向到 HTTPS(生产域名) server { listen 80; listen [::]:80; server_name api.example.com; location /.well-known/acme-challenge/ { root /var/www/certbot; } location / { return 301 https://$server_name$request_uri; } } # 开发环境 - 直接代理,不重定向到 HTTPS server { listen 80; listen [::]:80; server_name localhost api-gateway host.docker.internal; # 开发环境直接代理,不强制 HTTPS include /etc/nginx/conf.d/services/*.conf; # 健康检查 location /health { access_log off; return 200 '{"status":"healthy","timestamp":"$time_iso8601"}\n'; add_header Content-Type application/json; } # 根路径 location / { return 200 '{"status":"ok","service":"api-gateway","timestamp":"$time_iso8601"}\n'; add_header Content-Type application/json; } } # API 网关主配置 server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name api.example.com; # SSL 证书配置 ssl_certificate /etc/nginx/ssl/cert.pem; ssl_certificate_key /etc/nginx/ssl/key.pem; ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m; ssl_session_tickets off; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers off; # 客户端请求大小限制 client_max_body_size 50M; client_body_buffer_size 16k; # 超时配置 proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; # 安全响应头 add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always; # 根路径 - 健康检查 location / { return 200 '{"status":"ok","service":"api-gateway","timestamp":"$time_iso8601"}\n'; add_header Content-Type application/json; } # 健康检查端点 location /health { access_log off; return 200 '{"status":"healthy","timestamp":"$time_iso8601"}\n'; add_header Content-Type application/json; } # 包含各服务路由配置 include /etc/nginx/conf.d/services/*.conf; # 错误处理 error_page 404 /404.json; location = /404.json { return 404 '{"error":"Not Found","message":"The requested resource was not found","code":404}\n'; add_header Content-Type application/json; } error_page 500 502 503 504 /50x.json; location = /50x.json { return 500 '{"error":"Internal Server Error","message":"Something went wrong","code":500}\n'; add_header Content-Type application/json; } }