# Nginx配置 - IOPaint API服务 user nginx; worker_processes auto; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; # 日志格式 log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for" ' 'rt=$request_time uct="$upstream_connect_time" ' 'uht="$upstream_header_time" urt="$upstream_response_time"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # 客户端配置 client_max_body_size 20M; # 允许上传最大20MB client_body_timeout 60s; client_header_timeout 60s; # Gzip压缩 gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss; # 限流配置(防止API滥用) limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s; limit_req_status 429; # Upstream配置 upstream api_backend { server api:8080; keepalive 32; } # HTTP服务器(重定向到HTTPS) server { listen 80; server_name _; # 健康检查端点(不需要HTTPS) location /api/v1/health { proxy_pass http://api_backend; } # 其他请求重定向到HTTPS location / { return 301 https://$host$request_uri; } } # HTTPS服务器 server { listen 443 ssl http2; server_name your-domain.com; # 替换为你的域名 # SSL证书配置 ssl_certificate /etc/nginx/ssl/cert.pem; ssl_certificate_key /etc/nginx/ssl/key.pem; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; # API路由 location /api/ { # 限流:每秒10个请求,突发20个 limit_req zone=api_limit burst=20 nodelay; # 代理设置 proxy_pass http://api_backend; 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; proxy_set_header Connection ""; # 超时设置(图片处理可能较慢) proxy_connect_timeout 60s; proxy_send_timeout 120s; proxy_read_timeout 120s; # 缓冲区设置 proxy_buffering off; proxy_request_buffering off; } # 文档路由 location ~ ^/(docs|redoc|openapi.json) { proxy_pass http://api_backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # 根路径 location / { proxy_pass http://api_backend; proxy_set_header Host $host; } # 自定义错误页面 error_page 429 /429.html; location = /429.html { internal; default_type application/json; return 429 '{"error": "Too Many Requests", "detail": "Rate limit exceeded. Please try again later."}'; } error_page 502 503 504 /50x.html; location = /50x.html { internal; default_type application/json; return 503 '{"error": "Service Unavailable", "detail": "The service is temporarily unavailable. Please try again later."}'; } } }