首页 > 解决方案 > 如何使用 AWS Lambda 和 Cloudfront 删除 .html 扩展名

问题描述

  1. 我将网站的源代码存储在 AWS S3 中,并且我正在使用 AWS Cloudfront 来交付我的内容。
  2. 我想使用 AWS Lamda@Edge 从通过 Cloudfront 提供的所有 Web 链接中删除 .html 扩展名。
  3. 我需要的输出应该是 www.example.com/foo 而不是 www.example.com/foo.html 或 example.com/foo1 而不是 example.com/foo1.html。

请帮助我实现这一点,因为我找不到明确的解决方案。我已经提到了这篇文章中提到的第 3 点:https ://forums.aws.amazon.com/thread.jspa?messageID=796961&tstart=0 。但目前尚不清楚我需要做什么。

PFB lambda 代码,我该如何修改它-

const config = {
    suffix: '.html',
    appendToDirs: 'index.html',
    removeTrailingSlash: false,
};

const regexSuffixless = /\/[^/.]+$/; // e.g. "/some/page" but not "/", "/some/" or "/some.jpg"
const regexTrailingSlash = /.+\/$/; // e.g. "/some/" or "/some/page/" but not root "/"

exports.handler = function handler(event, context, callback) {
    const { request } = event.Records[0].cf;
    const { uri } = request;
    const { suffix, appendToDirs, removeTrailingSlash } = config;

    // Append ".html" to origin request
    if (suffix && uri.match(regexSuffixless)) {
        request.uri = uri + suffix;
        callback(null, request);
        return;
    }

    // Append "index.html" to origin request
    if (appendToDirs && uri.match(regexTrailingSlash)) {
        request.uri = uri + appendToDirs;
        callback(null, request);
        return;
    }

    // Redirect (301) non-root requests ending in "/" to URI without trailing slash
    if (removeTrailingSlash && uri.match(/.+\/$/)) {
        const response = {
            // body: '',
            // bodyEncoding: 'text',
            headers: {
                'location': [{
                    key: 'Location',
                    value: uri.slice(0, -1)
                 }]
            },
            status: '301',
            statusDescription: 'Moved Permanently'
        };
        callback(null, response);
        return;
    }

    // If nothing matches, return request unchanged
    callback(null, request);
};

请帮助我从我的网站中删除 .html 扩展名,以及我需要将哪些更新的代码粘贴到我的 AWS Lambda 中提前谢谢!

标签: amazon-web-servicesaws-lambdaamazon-cloudfrontaws-serverlessaws-lambda-edge

解决方案


推荐阅读