如何将Nginx作为Google Cloud Storage签名URL的代理(支持上传下载)
Nginx代理Google Cloud Storage签名URL(支持上传与下载)
需求概述
- 客户端将Google Cloud Storage(GCS)签名URL的域名替换为Nginx域名(如
https://noman.me)发起请求 - Nginx收到请求后,仅替换域名,保留完整路径和查询参数转发至
https://storage.googleapis.com,同时支持上传(PUT/POST)和下载(GET) - 签名URL通过GCS官方SDK生成,已验证可用:
// 核心配置(冗余代码已省略) const options: GetSignedUrlConfig = { version: 'v4', action: 'write', expires: Date.now() + signedUrlExpirationTimeFromConfig * 1000, virtualHostedStyle: true, } const [signedUrl] = await this.storage .bucket(bucketName) .file(remoteFilePath) .getSignedUrl(options)
现有配置问题
当前Nginx配置未生效,核心问题有两点:
- proxy_pass路径错误:请求URL中已包含
bucket-name,但配置中额外拼接了bucket-name/,导致转发路径重复(例如实际转发路径变为storage.googleapis.com/bucket-name/bucket-name/cat.jpeg) - Host头配置错误:GCS签名URL验证依赖
Host头匹配签名时的域名,当前配置将Host设为自身域名noman.me,导致签名验证失败
修正后的Nginx配置
server { listen 80; server_name noman.me; access_log /var/log/nginx/front-access.log; error_log /var/log/nginx/front-error.log; # 适配大文件上传,根据实际需求调整 client_max_body_size 100M; location / { # 直接转发完整路径和查询参数,无需额外拼接bucket-name proxy_pass https://storage.googleapis.com$uri$is_args$query_string; # 关键:设置Host为GCS官方域名,保证签名验证通过 proxy_set_header Host storage.googleapis.com; # 禁用升级相关头,避免干扰GCS请求 proxy_set_header Upgrade ""; proxy_set_header Connection ""; proxy_http_version 1.1; # 转发客户端真实IP相关头(可选,用于GCS访问日志溯源) 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; # CORS配置,适配浏览器跨域请求 if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, PATCH, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } add_header 'Access-Control-Allow-Origin' '*' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, PATCH, OPTIONS' always; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always; } }
关键说明
- 路径转发逻辑:使用
$uri$is_args$query_string确保完整转发请求路径和查询参数,$is_args会自动判断是否有查询参数(有则带?,无则为空),避免多余的?符号 - Host头必须正确:GCS V4签名URL会将
Host头纳入签名验证范围,因此必须设置为storage.googleapis.com,否则会返回403签名无效错误 - 移除Upgrade/Connection头:原配置中的
Upgrade和Connection头是用于WebSocket的,会干扰GCS的常规上传下载请求,需清空 - CORS简化:将分散的请求方法CORS配置合并,用
always确保响应头在所有状态码下都能返回(包括4xx/5xx错误)
内容的提问来源于stack exchange,提问作者Noman Ur Rehman
相关产品推荐
相关产品推荐

