【问题标题】:AWS static website - how to connect subdomains with subfoldersAWS 静态网站 - 如何将子域与子文件夹连接起来
【发布时间】:2022-01-20 17:22:26
【问题描述】:
我想设置 S3 静态网站并连接到我的域(例如域:example.com)。
在这个 S3 存储桶中,我想创建一个特定文件夹(名称 content)和许多不同的子文件夹,然后我想将这些子文件夹与适当的子域连接起来,例如
- 文件夹 content/foo 应该可以从子域 foo.example.com 获得,
- fodler content/bar 应该可以从子域 bar.example.com 获得。
任何 content 子文件夹都应该可以从具有相同前缀名称(如文件夹名称)的子域自动获得。
对于这个问题的任何可能的解决方案,我将不胜感激。我应该使用重定向选项还是有更好的解决方案?提前感谢您的帮助。
【问题讨论】:
标签:
amazon-s3
dns
subdomain
wildcard-subdomain
static-pages
【解决方案1】:
我的解决方案基于此视频:
https://www.youtube.com/watch?v=mls8tiiI3uc
由于上面的视频没有解释子域问题,这里有一些额外的事情要做:
- 我们应该向 AWS Route53 人质区添加记录 A,记录名称为“*.domainname”,值为边缘地址
- 我们还应该在证书域中添加“*.domainname”- 以获得通配符域的证书
- 在设置 Cloudfront 分发时,我们应该将“www.domainname”和“*.domainname”添加到“Alternate domain name (CNAME)”部分
- 从子域到子文件夹的重定向/转发是通过 Lambda@Edge 功能实现的(功能应该有所改进):
'use strict';
exports.handler = (event, context, callback) => {
const path = require("path");
const remove_suffix = ".domain.com";
const host_with_www = "www.domain.com"
const origin_hostname = "www.domain.com.s3-website.eu-west-1.amazonaws.com";
const request = event.Records[0].cf.request;
const headers = request.headers;
const host_header = headers.host[0].value;
if (host_header == host_with_www) {
return callback(null, request);
}
if (host_header.startsWith('www')) {
var new_host_header = host_header.substring(3,host_header.length)
}
if (typeof new_host_header === 'undefined') {
var new_host_header = host_header
}
if (new_host_header.endsWith(remove_suffix)) {
// to support SPA | redirect all(non-file) requests to index.html
const parsedPath = path.parse(request.uri);
if (parsedPath.ext === "") {
request.uri = "/index.html";
}
request.uri =
"/" +
new_host_header.substring(0, new_host_header.length - remove_suffix.length) +
request.uri;
}
headers.host[0].value = origin_hostname;
return callback(null, request);
};
- Lambda@Edge 只是与特定 Cloudfront 发行版连接的 Lambda 函数
- 需要为 Lambda 执行添加到 Cloudfront 分发附加设置(如果我们想对不同的子域进行不同的重定向,则需要此设置,而不是所有重定向都指向主目录或可能指向将被缓存的第一个目录 - 第一个请求到我们的 Cloudfront 域):