首页 > 解决方案 > S3 静态网站仅使用 /index.html 打开

问题描述

我正在Vue.JS使用Terraform. 如果我使用Terraform将实际文件上传到存储桶然后打开站点/index.html失败并给我一个下载对话框。如果我在控制台中手动上传文件,我可以通过访问/.

我的 terraform 文件在下面,我错过了什么?

provider "aws" {
  access_key = var.aws_access_key
  secret_key = var.aws_secret_key
  version    = "~> 3.0"
  region     = var.region
}

# create a bucket
resource "aws_s3_bucket" "aws_s3_bucket_portal" {
  bucket  = "my-silly-test"
  acl     = "public-read"

  website {
    index_document = "index.html"
    error_document = "index.html"
  }
}

# create bucket policy
resource "aws_s3_bucket_policy" "portal_policy" {
  bucket = aws_s3_bucket.aws_s3_bucket_portal.id

  policy = <<POLICY
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "${aws_s3_bucket.aws_s3_bucket_portal.arn}/*"
        }
    ]
}
POLICY
}

variable "mime_types" {
  default = {
    htm   = "text/html"
    html  = "text/html"
    css   = "text/css"
    js    = "application/javascript"
    map   = "application/javascript"
    json  = "application/json"
    png   = "image/png"
    jpg   = "image/jpg"
    jpeg  = "image/jpg"
    gif   = "image/gif"
    svg   = "image/svg+xml"
  }
}

# upload root files to the bucket
resource "aws_s3_bucket_object" "website_files" {
  for_each = fileset(var.upload_directory, "**/*.*")
  bucket = aws_s3_bucket.aws_s3_bucket_portal.bucket
  key = replace(each.value, var.upload_directory, "")
  source = "${var.upload_directory}/${each.value}"
  etag = filemd5("${var.upload_directory}/${each.value}")
  # acl = "public-read"
  content_type = lookup(var.mime_types, split(".", each.value)[length(split(".", each.value))-1], "text/html")
}

标签: amazon-web-servicesvue.jsamazon-s3terraform

解决方案


所以,事实证明这就是 S3 的样子。上传到 S3 时,需要设置 mime 类型,最好的方法是使用命令行上传,而不是 terraform。

然而...

如果您使用 terraform 上传文件,请确保设置 mime 类型。然后,如果您使用 CloudFront 托管站点,问题就会消失,因为它将决定向您的客户返回什么。类型仍然需要存在。


推荐阅读