vue.js S3静态网站仅使用/index. html打开

rxztt3cl  于 2022-11-17  发布在  Vue.js
关注(0)|答案(2)|浏览(122)

我正在使用Terraform创建并上传一个S3静态Vue.JS站点。如果我使用Terraform将实际文件上传到bucket,则使用/index.html打开站点会失败,并显示一个下载对话框。如果我在控制台中手动上传文件,则可以通过访问/查看站点。
我的地形文件在下面,我错过了什么?

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")
}
c3frrgcw

c3frrgcw1#

所以,事实证明这就是S3的简单方式。当上传到S3时,mime类型需要设置,最好的方法是使用命令行上传,而不是terraform。
可是......
如果你使用terraform上传文件,确保你设置了mime类型。然后,如果你使用CloudFront来托管网站,问题就消失了,因为它将决定返回给你的客户端的内容。类型仍然需要在那里。

relj7zay

relj7zay2#

感谢马特提出这个问题和你的后续行动,这导致了我的解决方案!
当使用Terraform将index.html文件上传到存储桶以便用作S3静态网站的一部分时,请将content_type参数设置为“text/html”。

# Add object to bucket
resource "aws_s3_object" "object_index" {
  bucket       = aws_s3_bucket.bucket_tf.bucket
  key          = "index.html"
  source       = "bucket_objects/index.html"
  content_type = "text/html"

  etag = filemd5("bucket_objects/index.html")
}

以下是您可以为S3对象定义的不同内容类型的列表。https://www.ibm.com/docs/en/aspera-on-cloud?topic=SS5W4X/dita/content/aws_s3_content_types.htm
一个Terraform模板,用于创建配置为托管静态网站的S3存储桶。添加了一个存储桶策略,该策略是公众访问静态网站所必需的。index.html文件作为对象上载到存储桶,用作静态网站的主页。https://github.com/thompsizzle/cloud-infrastructures/tree/main/AWS/S3_hello_world

相关问题