AWS S3存储桶下React项目i18n路径及查询参数语言检测异常
问题根因
- S3重定向规则丢失了原始请求的路径与查询参数
你当前配置的S3重定向规则在触发404/403跳转时存在两个问题:
- 没有开启查询参数透传,原始请求的查询字符串会被直接丢弃
- 重定向时会把所有原始路径拼到
#!/之后放到hash段,而i18next-browser-languagedetector默认不会从hash段中读取路径或查询参数,导致检测器拿不到你设置的语言值,只能走兜底语言。
- 查询参数键名不匹配
你i18n配置里指定的查询参数键是lng,但你测试时用的是lang,二者不一致也会导致检测失效。
解决方案
方案1:保留hash路由模式
- 第一步:修改S3重定向规则,增加透传查询参数的配置,修改后的规则如下:
[ { "Condition": { "HttpErrorCodeReturnedEquals": "404" }, "Redirect": { "HostName": "my-bucket-name.s3-website-sa-east-1.amazonaws.com", "ReplaceKeyPrefixWith": "#!/", "PassQueryString": true } }, { "Condition": { "HttpErrorCodeReturnedEquals": "403" }, "Redirect": { "HostName": "my-bucket-name.s3-website-sa-east-1.amazonaws.com", "ReplaceKeyPrefixWith": "#!/", "PassQueryString": true } } ]
- 第二步:调整i18n检测配置,首先统一查询参数名:可以把i18n配置里的
lookupQuerystring改成lang,或者测试时使用?lng=xx的参数格式。
如果需要从hash路径(比如#!/en/xxx)里读取语言,需要新增自定义检测器:
const customHashDetector = { name: 'hashPath', lookup(options) { const hash = window.location.hash; const match = hash.match(/#!\/([a-z]{2})\//); return match ? match[1] : undefined; } } // 初始化i18n前注册自定义检测器 LanguageDetector.addDetector(customHashDetector); // 修改detection配置的order const options = { order: ['hashPath', 'querystring'], lookupQuerystring: 'lng', };
方案2:切换为BrowserRouter(更推荐)
React项目更常用BrowserRouter模式,不需要hash前缀,修改更简单:
- 修改S3重定向规则,触发404/403时直接返回index.html,状态码设为200:
[ { "Condition": { "HttpErrorCodeReturnedEquals": "404" }, "Redirect": { "HostName": "my-bucket-name.s3-website-sa-east-1.amazonaws.com", "ReplaceKeyWith": "index.html", "HttpRedirectCode": "200", "PassQueryString": true } }, { "Condition": { "HttpErrorCodeReturnedEquals": "403" }, "Redirect": { "HostName": "my-bucket-name.s3-website-sa-east-1.amazonaws.com", "ReplaceKeyWith": "index.html", "HttpRedirectCode": "200", "PassQueryString": true } } ]
- 把React路由切换为BrowserRouter模式,此时原始路径和查询参数都会完整保留,不需要额外调整i18n的检测逻辑,只需要统一查询参数键名即可正常检测。
调试建议
开启i18n的debug模式后,查看浏览器控制台的日志,可以清晰看到每一步检测的来源和取值,快速定位是参数丢失还是匹配规则问题。
内容的提问来源于stack exchange,提问作者Ann
相关产品推荐
相关产品推荐

