原因是默认情况下,AWS S3并不支持React Router的路由系统,必须通过配置Amazon CloudFront发行网络所需的文件,并在“Error Pages”中添加自定义错误页面,以保证正确的路由。
下面是一份示例代码,供参考:
1.在本地React项目中运行以下命令,创建生产构建:
npm run build
2.将构建输出上传到S3:
aws s3 cp build s3://my-bucket-name --recursive --acl public-read
3.配置CloudFront:
首先,您需要在CloudFront控制台的“分配”部分中创建分配。
其次,您需要配置两个origin:
一个S3 origin(您的静态文件将从此处获得);
一个自定义origin,指向您的服务器。
接下来,将您的错误页面配置为“/index.html”。
最后,您需要配置行为,以便始终将URL重写为“/index.html”。
以下是一个CloudFormation模板代码块,该模板将自动执行这些步骤:
"Resources": { "StaticContentBucket": { "Type": "AWS::S3::Bucket", "DeletionPolicy": "Retain", "Properties": { "BucketName": "my-bucket-name" } }, "StaticContent": { "Type": "Custom::S3Upload", "Properties": { "ServiceToken": { "Fn::GetAtt": ["uploadLambda", "Arn"]}, "Bucket": { "Ref": "StaticContentBucket" }, "Sources": [ { "Path": "./build", "Exclusions": [ "node_modules/", "src/", "public/**", "package.json", "package-lock.json", "README.md", "yarn.lock" ] } ] }, "DependsOn": [ "StaticContentBucket" ] }, "CloudFrontOriginAccessIdentity": { "Type": "AWS::CloudFront::CloudFrontOriginAccessIdentity", "Properties": { "CloudFrontOriginAccessIdentityConfig": { "Comment": "Allow access to my S3 bucket" } } }, "CloudFrontWebDistribution": { "Type": "AWS::CloudFront::Distribution", "Properties": { "DistributionConfig": { "Origins": [ { "DomainName": { "Fn::GetAtt": ["StaticContentBucket","DomainName"] }, "Id": "S3-my-bucket-name", "S3OriginConfig": { "OriginAccessIdentity": "origin-access-identity/cloudfront/E33XYZ9012345" } }, { "DomainName": "my-domain.example.com", "Id": "Custom-my-domain.example.com", "CustomOriginConfig": { "HTTPPort": 80, "HTTPSPort": 443, "OriginProtocolPolicy": "https-only", "OriginSslProtocols": ["TLSv1.2"] } } ], "DefaultRootObject": "index.html", "PriceClass": "PriceClass_All", "Enabled": "true", "DefaultCacheBehavior": { "AllowedMethods": ["GET", "HEAD"], "Compress