- Newest
- Most votes
- Most comments
If you prefer to keep things simpler and don't require the advanced capabilities provided by Lambda@Edge, you can use S3 built-in website redirection feature.
Here's how: Create a new S3 bucket for website redirection (e.g., "example-redirects-bucket").
In this bucket, configure a simple HTML file for each redirect. For example, if you want to redirect "/old-url" to "/new-url", create an HTML file named "index.html" in the "old-url" folder with the following content:
html Copy code
<!DOCTYPE html> <html> <head> <meta http-equiv="refresh" content="0;url=https://example.com/new-url"> </head> </html> Make sure that "example-redirects-bucket" is set up as a static website and allows public access.In your main S3 bucket where your website is hosted, configure a routing rule in the S3 bucket's properties to redirect requests for "/old-url" to the corresponding HTML file in "example-redirects-bucket." Happy Learning
With a large number of redirects to handle, I think you'd be better off using Lambda@Edge along with an external data source. This way, you don't need to update your Lambda code every time you need to add/change a redirect - instead, you just modify the data source. DynamoDB Global Tables is a good option for this. Take a look at this blog post which discusses a variety of approaches. Be sure to attach your Lambda@Edge function to the Origin Request trigger so that the redirect responses are stored in the CloudFront cache.
Thanks Paul! For now, I have 364 redirects. To keep things simpler I use a redirect.json file in my function deployment package. When the redirect happens I get "Miss from cloudfront" in the header. I was expecting "Hit from cloudfront". It's right? My Code: const redirects = require('./redirects.json').map( ({ source, destination }) => ({ source, destination }) );
exports.handler = async event => {
let request = event.Records[0].cf.request; for (const { source, destination } of redirects) { if (request.uri == source) { //Generate HTTP redirect response to a different landing page. return { status: '301', statusDescription: 'Moved Permanently', headers: { 'location': [{ key: 'Location', value: destination, }], 'cache-control': [{ key: 'Cache-Control', value: "max-age=3600" }], }, }; } } return request;
};
Relevant content
- asked 2 years ago
- Accepted Answerasked 3 years ago
- AWS OFFICIALUpdated 2 years ago
- AWS OFFICIALUpdated 2 years ago
- AWS OFFICIALUpdated a month ago
- AWS OFFICIALUpdated a year ago
Thank Waseem for your prompt answer. I just implemented this solution and it works! But, what happens if I need to redirect more than 50 urls? Can I do it with routing rules in the main S3 bucket's?