You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让S3对所有404请求返回index.html而非重定向?

Got it, let's break this down for you—since you're hosting your SPA on S3, there are two common setups you might be using, and each has a straightforward fix to get that routing fallback working. Here's how to handle both scenarios:

1. Using S3 Static Website Hosting Directly

If you're serving your SPA directly from S3's built-in static website feature (no CloudFront in front), this is super simple:

  • Head to your S3 bucket in the AWS Console.
  • Jump to the Properties tab, scroll down to the Static website hosting section, and confirm it's turned on.
  • In the Error document field, type index.html. This tells S3 to send your SPA's main page every time a user hits a URL that doesn't match an actual file in the bucket (which is exactly the 404 scenario we need to handle for SPA routing).
  • Save your changes, and you're done! Now any request to a non-existent path will load index.html, letting your JS router take over.

If you're using CloudFront (which is a good call for HTTPS, caching, and global performance), you'll need to set up a custom error response:

  • Open your CloudFront distribution in the AWS Console, then go to the Behaviors tab.
  • Select your default behavior (or create a new one if you have specific path rules) and click Edit.
  • Scroll down to the Error Pages section, then click Create custom error response.
  • Fill in the details:
    • HTTP error code: Pick 404: Not Found
    • Customize error response: Toggle to Yes
    • Response page path: Enter /index.html
    • HTTP response code: Choose 200: OK (this is critical—you don't want the browser to receive a 404 status, which would break your SPA's routing logic)
  • Save the custom error response, then save the behavior changes.
  • Wait a few minutes for CloudFront to deploy the update (distributions can take 5-10 minutes to propagate changes). Once done, any invalid URL will serve index.html with a 200 status, which plays perfectly with your SPA's router.

Pro tip: Double-check that your SPA's router is configured for client-side routing (like HTML5 history mode if you prefer clean URLs without hashes). This S3/CloudFront setup supports both modes, but history mode relies entirely on this server-side fallback to work correctly.

内容的提问来源于stack exchange,提问作者Mehran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:50:49