【问题标题】:Lambda@edge redirect gets in a redirect loopLambda@edge 重定向进入重定向循环
【发布时间】:2019-04-21 20:26:01
【问题描述】:

我在 aws s3 上有一个静态网站。已设置路线 53 和云前,一切顺利。 s3 Bucket 设置为将 index.html 作为索引文档。

现在我添加了另一个名为 index-en.html 的文件,当请求的国家/地区是任何其他国家/地区而不是我的祖国时应该提供该文件。

为此,我添加了一个带有以下代码的 lambda@edge 函数:

'use strict';

/* This is an origin request function */
exports.handler = (event, context, callback) => {
    const request = event.Records[0].cf.request;
    const headers = request.headers;

    /*
     * Based on the value of the CloudFront-Viewer-Country header, generate an
     * HTTP status code 302 (Redirect) response, and return a country-specific
     * URL in the Location header.
     * NOTE: 1. You must configure your distribution to cache based on the
     *          CloudFront-Viewer-Country header. For more information, see
     *          http://docs.aws.amazon.com/console/cloudfront/cache-on-selected-headers
     *       2. CloudFront adds the CloudFront-Viewer-Country header after the viewer
     *          request event. To use this example, you must create a trigger for the
     *          origin request event.
     */

    let url = 'prochoice.com.tr';
    if (headers['cloudfront-viewer-country']) {
        const countryCode = headers['cloudfront-viewer-country'][0].value;
        if (countryCode === 'TR') {
            url = 'prochoice.com.tr';
        } else {
            url = 'prochoice.com.tr/index-en.html';
        }
    }

    const response = {
        status: '302',
        statusDescription: 'Found',
        headers: {
            location: [{
                key: 'Location',
                value: url,
            }],
        },
    };
    callback(null, response);
};

我还编辑了云前端行为以将 Origin 和 Viewer-country 标头列入白名单,并设置云前端 Viewer-Request 事件和 lambda 函数 ARN 关系。

但是我收到“重定向错误太多”。

我有两个问题:

  1. 如何纠正“重定向过多错误”?
  2. 对于“TR”以外的查看者,默认登录页面应为 index-en.html,可通过导航菜单访问另外 2 个英文页面。因此,当用户从页面导航请求特定页面时,他们应该能够访问这些页面,当没有请求页面时,应该提供默认登录页面。

感谢帮助。 谢谢。

【问题讨论】:

    标签: amazon-s3 amazon-cloudfront aws-lambda-edge


    【解决方案1】:

    您正在创建一个重定向循环,因为无论您的测试结果如何,您都将查看者返回到同一个站点、同一个页面。

    if (countryCode === 'TR') {
        return callback(null, request);
    } else {
    ...
    

    callback(null,request) 告诉 CloudFront 继续处理请求,而不是生成响应。在回调之前使用return 会导致其余的触发代码无法运行。

    【讨论】:

    • 无论他们请求什么页面,这是否会将 countryCode 不是 TR 的用户始终重定向到 index-en.html?
    • 您不能“无论他们请求什么页面”重定向用户,除非您首先确认他们没有请求您计划将他们重定向到的页面——这就是您有重定向的原因环形。从您的问题中不清楚 所有 请求应该转到一个页面。您可能需要通过编辑来澄清您的问题,准确描述在不同条件下预期的行为。
    • 我已对原始问题进行了编辑。谢谢大家的帮助。
    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多