我可以将AWS API Gateway用作S3网站的反向代理吗? [英] Can I use AWS API Gateway as a reverse proxy for a S3 website?
问题描述
我在AWS S3上有一个无服务器网站.但是S3有一个我想克服的局限性:它不允许我拥有友好的URL.
I have a serverless website on AWS S3. But S3 have a limitation that I want to overcome: it don't allow me to have friendly URLs.
例如,我想替换URL:
For example, I would like to replace URL:
www.mywebsite.com/user.html?login=daniel
www.mywebsite.com/user.html?login=daniel
使用此网址友好:
www.mywebsite.com/user/daniel
www.mywebsite.com/user/daniel
因此,我想知道是否可以将Lambda与API Gateway一起使用来实现这一目标.
So, I would like to know if I can use Lambda together with API Gateway to achieve this.
我的想法是:
API网关---> Lambda函数--->获取S3资源
API Gateway ---> Lambda function ---> fetch S3 resource
API网关将获取ANY请求,并将信息传递给Lambda函数,该函数将使用请求URL处理某些逻辑(可能包括一些数据库查询),然后从S3中获取资源.
The API Gateway will get ANY request, and pass information to a Lambda funcion, that will process some logic using the request URL (including maybe some database query) and then fetch the resource from S3.
我知道AWS API Gateway的主要目的是成为REST API的网关,但是我们也可以将其用作整个网站的代理吗?
I know AWS API Gateway main purpose is to be a gateway to REST APIs, but can we also use it as a proxy to an entire website?
推荐答案
可以将API Gateway用作S3网站的反向代理.
It is possible to use API Gateway as a reverse proxy for a S3 website.
我能够按照以下步骤进行操作:
I was able to do that following steps below:
- 在AWS API Gateway中,使用资源路径="{proxy +}"创建一个代理资源"
- 转到AWS Certificate Manager,并为您的网站(* .mywebsite.com)请求通配符证书
- AWS会告诉您在域名注册机构中创建CNAME记录,以验证您是否拥有该域名
- 验证证书之后,转到AWS API Gateway并创建一个自定义域名(单击自定义域名",然后单击创建自定义域名").在域名"中,输入您的域(www.mywebsite.com),然后选择您刚创建的ACM证书(上述步骤1).创建一个路径为"/"的基本路径映射",并在目标"中选择您的API和阶段.
- 之后,您将需要添加另一个CNAME记录,以及为该自定义域名生成的CloudFront目标域名".
在Lambda中,我们可以路由请求:
In the Lambda, we can route the requests:
'use strict';
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const myBucket = 'myBucket';
exports.handler = async (event) => {
var responseBody = "";
if (event.path=="/") {
responseBody = "<h1>My Landing Page</h1>";
responseBody += "<a href='/xpto'>link to another page</a>";
return buildResponse(200, responseBody);
}
if (event.path=="/xpto") {
responseBody = "<h1>Another Page</h1>";
responseBody += "<a href='/'>home</a>";
return buildResponse(200, responseBody);
}
if (event.path=="/my-s3-resource") {
var params = {
Bucket: myBucket,
Key: 'path/to/my-s3-resource.html',
};
const data = await s3.getObject(params).promise();
return buildResponse(200, data.Body.toString('utf-8'));
}
return buildResponse(404, '404 Error');
};
function buildResponse(statusCode, responseBody) {
var response = {
"isBase64Encoded": false,
"statusCode": statusCode,
"headers": {
"Content-Type" : "text/html; charset=utf-8"
},
"body": responseBody,
};
return response;
}
这篇关于我可以将AWS API Gateway用作S3网站的反向代理吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!