by

How To: HTTP redirects with API Gateway and Lambda

Update (2017-08-15): Recent service updates have removed the need for the workarounds described below, though they may still be useful in some cases, or for historical context.

Achieving HTTP redirects with API Gateway and Lambda is now trivial with the addition of Proxy integrations.

Simply define an API with an ‘aws_proxy’ integration type, and implement your Lambda function to explicitly return the redirect status code and Location header.

Lambda Function

i.e.

'use strict';
 
exports.handler = function(event, context, callback) {
    var response = {
        statusCode: 301,
        headers: {
            "Location" : "http://ryangreen.ca"
        },
        body: null
    };
    callback(null, response);
};

Swagger

---
swagger: "2.0"
info:
  version: "2017-08-15T19:29:52Z"
  title: "redirect test"
basePath: "/prod"
schemes:
- "https"
paths:
  /redirect2:
    x-amazon-apigateway-any-method:
      x-amazon-apigateway-integration:
        uri: "arn:aws:apigateway:[REGION]:lambda:path/2015-03-31/functions/arn:aws:lambda:[REGION]:[ACCOUNT_ID]:function:[FUNCTION_NAME]/invocations"
        passthroughBehavior: "when_no_match"
        httpMethod: "POST"
        type: "aws_proxy"

——

API Gateway recently released support for mapping response bodies to response headers. One application of this feature is to enable conditional HTTP redirects in your API Gateway/Lambda API.

There are a couple of ways to achieve 30x redirects in your API Gateway/Lambda API.

Option 1: 30X as “default” response

This option is preferred if your API method always redirects (i.e. never returns a normal 2XX response).

1) Define a method response with status 302, and a “Location” header defined
2) Define a “default” integration response mapping with blank regex, mapping to 302.
3) For this response, define a “Location” header mapping from the redirect URL returned in your Lambda function. i.e. “integration.response.body.location”
3) Configure your lambda function to return the redirect location in the body, i.e.

context.succeed({location : "http://example.com"})

Swagger example

/lambdaredirect-default:
    get:
      produces:
      - "application/json"
      parameters: []
      responses:
        200:
          description: "200 response"
          schema:
            $ref: "#/definitions/Empty"
          headers: {}
        302:
          description: "302 response"
          headers:
            Location:
              type: "string"
      x-amazon-apigateway-integration:
        responses:
          default:
            statusCode: "302"
            responseParameters:
              method.response.header.Location: "integration.response.body.location"
        uri: "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:[ACCOUNT_ID]:function:redirect-default/invocations"
        httpMethod: "POST"
        type: "aws"

Lambda function

exports.handler = function(event, context) {
    context.succeed({
        location : "https://example.com"
    });
};

Option 2: 30X as an error response

This option allows your method to return both “successful” (2XX) and redirect outcomes, but requires you to model redirects in your lambda function as errors.

1) Define a method response with status 302, and a “Location” header defined. Leave the “default” integration 2XX response with blank regex, mapped to your 2XX method response.
2) Define the redirect integration response mapping with regex “http.*”, mapped to your 30X response.
3) For this response, map the redirect URL returned in the error message of your lambda function to your “Location” header: “integration.response.body.errorMessage”
3) Configure your lambda function to return the redirect location as the error message, i.e.

context.fail("http://example.com")

or

throw new RuntimeException("http://example.com")

4) Optional: If you don’t want to expose the lambda error response body to the client, define a mapping template on the redirect response to nullify the response body. You can use a template with a comment to render an empty response.

Swagger example

 /lambdaredirect-error:
    get:
      produces:
      - "application/json"
      parameters: []
      responses:
        200:
          description: "200 response"
          schema:
            $ref: "#/definitions/Empty"
          headers: {}
        302:
          description: "302 response"
          headers:
            Location:
              type: "string"
      x-amazon-apigateway-integration:
        responses:
          default:
            statusCode: "200"
          https://.*:
            statusCode: "302"
            responseParameters:
              method.response.header.Location: "integration.response.body.errorMessage"
            responseTemplates:
              application/json: "## intentionally blank"
        uri: "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:[ACCOUNT_ID]]:function:redirect-error/invocations"
        httpMethod: "POST"
        type: "aws"

Lambda function

exports.handler = function(event, context) {
    context.fail("https://example.com");
};

Here’s a full Gist with the example.

Cheers,
Ryan

Write a Comment

Comment

  1. Thanks for writing this up! I’m afraid I spent the last 2+ hours reading the conflicting and not very helpful AWS Lambda/APIGateway docs, trying to do just this. It’s amazing how many steps and models they require to just do a redirect, which is one of the most common and most trivial of HTTP tasks.

  2. Hi,

    The post describes how to do it with node js lambda. Do you know whether it’s possible to do something similar with a Python lambda? It looks like the context object has a different purpose there, and the only possible response is json.

    Thanks,
    Benny

  3. Here’s option 3 – which I think is the best one

    The API Gateway status codes are triggered by ErrorMessage. So I’d use it for the error code. Then I’d pass the body or in the case of 302, the location in the errorType. It’s a little odd to read. E.g. { errorType: “Sorry can’t find the resource”, errorMessage: “404” }. But this way I can then map the response.header.location to errorType and still have full control for the other status codes.

    See it working here: https://github.com/ronaldwidha/index.lambda (click on the demo/test-harness/302 redirect)

Webmentions

  • take viagra under the tongue June 29, 2016

    take viagra under the tongue

    take viagra under the tongue

  • sildenafil suck June 29, 2016

    sildenafil suck

    sildenafil suck

  • cialis captions June 29, 2016

    cialis captions

    cialis captions

  • cialis 40 mg coupon June 29, 2016

    cialis 40 mg coupon

    cialis 40 mg coupon

  • sildenafil citrate 100 mg side effects June 29, 2016

    sildenafil citrate 100 mg side effects

    sildenafil citrate 100 mg side effects

  • buying canadian cialis June 29, 2016

    buying canadian cialis

    buying canadian cialis

  • natural cialis 2018 June 29, 2016

    natural cialis 2018

    natural cialis 2018

  • viagra canada by mail June 29, 2016

    viagra canada by mail

    viagra canada by mail

  • safe alternatives to viagra and cialis June 29, 2016

    safe alternatives to viagra and cialis

    safe alternatives to viagra and cialis

  • viagra pill 36 June 29, 2016

    viagra pill 36

    viagra pill 36

  • cialis for women June 29, 2016

    cialis for women

    cialis for women

  • viagra sex uncensored June 29, 2016

    viagra sex uncensored

    viagra sex uncensored

  • levitra 20 mg June 29, 2016

    levitra 20 mg

    levitra 20 mg

  • levitra reviews June 29, 2016

    levitra reviews

    levitra reviews

  • viagra porn June 29, 2016

    viagra porn

    viagra porn

  • viagra 100mg price June 29, 2016

    viagra 100mg price

    viagra 100mg price

  • cialis professional June 29, 2016

    cialis professional

    cialis professional

  • generic viagra 100mg June 29, 2016

    generic viagra 100mg

    generic viagra 100mg

  • mandy flores viagra June 29, 2016

    mandy flores viagra

    mandy flores viagra

  • natural viagra for men June 29, 2016

    natural viagra for men

    natural viagra for men

  • cialis vs viagra June 29, 2016

    cialis vs viagra

    cialis vs viagra

  • fucking on viagra June 29, 2016

    fucking on viagra

    fucking on viagra

  • generic viagra online June 29, 2016

    generic viagra online

    generic viagra online

  • dissolving sildenafil under the tongue June 29, 2016

    dissolving sildenafil under the tongue

    dissolving sildenafil under the tongue

  • cymbalta pupil June 29, 2016

    cymbalta pupil

    cymbalta pupil

  • generic names for keflex June 29, 2016

    generic names for keflex

    generic names for keflex

  • generics for celebrex June 29, 2016

    generics for celebrex

    generics for celebrex

  • azithromycin dosage for children June 29, 2016

    azithromycin dosage for children

    azithromycin dosage for children

  • amoxicillin 500mg for tooth infection June 29, 2016

    amoxicillin 500mg for tooth infection

    amoxicillin 500mg for tooth infection

  • cymbalta make me sleepy June 29, 2016

    cymbalta make me sleepy

    cymbalta make me sleepy

  • ic cephalexin side effects June 29, 2016

    ic cephalexin side effects

    ic cephalexin side effects

  • celebrex and indigestion June 29, 2016

    celebrex and indigestion

    celebrex and indigestion

  • side effects of azithromycin 250 mg June 29, 2016

    side effects of azithromycin 250 mg

    side effects of azithromycin 250 mg

  • amoxicillin and birth control pills June 29, 2016

    amoxicillin and birth control pills

    amoxicillin and birth control pills

  • demo viagra blog planet June 29, 2016

    demo viagra blog planet

    demo viagra blog planet

  • cialis covered for prostate cancer June 29, 2016

    cialis covered for prostate cancer

    cialis covered for prostate cancer

  • best generic viagra reviews June 29, 2016

    best generic viagra reviews

    best generic viagra reviews

  • familydick viagra dad June 29, 2016

    familydick viagra dad

    familydick viagra dad

  • cialis coverage ? June 29, 2016

    cialis coverage ?

    cialis coverage ?

  • sildenafil 100mg June 29, 2016

    sildenafil 100mg

    sildenafil 100mg

  • comprar cialis June 29, 2016

    comprar cialis

    comprar cialis

  • viagra boner June 29, 2016

    viagra boner

    viagra boner

  • actual sex with viagra June 29, 2016

    actual sex with viagra

    actual sex with viagra

  • will viagra expire June 29, 2016

    will viagra expire

    will viagra expire

  • 20 mg citalopram June 29, 2016

    20 mg citalopram

    20 mg citalopram

  • another drug like celebrex June 29, 2016

    another drug like celebrex

    another drug like celebrex

  • generic carvedilol brands June 29, 2016

    generic carvedilol brands

    generic carvedilol brands

  • buspirone and cannabis June 29, 2016

    buspirone and cannabis

    buspirone and cannabis

  • does buspar work June 29, 2016

    does buspar work

    does buspar work

  • bupropion er June 29, 2016

    bupropion er

    bupropion er

  • baclofen muscle weakness June 29, 2016

    baclofen muscle weakness

    baclofen muscle weakness

  • baclofen and oxycodone June 29, 2016

    baclofen and oxycodone

    baclofen and oxycodone

  • zithromax buy June 29, 2016

    zithromax buy

    zithromax buy

  • atorvastatin 2 June 29, 2016

    atorvastatin 2

    atorvastatin 2

  • aripiprazole happy June 29, 2016

    aripiprazole happy

    aripiprazole happy

  • how long does amoxicillin stay good June 29, 2016

    how long does amoxicillin stay good

    how long does amoxicillin stay good

  • norvasc generic equivalent June 29, 2016

    norvasc generic equivalent

    norvasc generic equivalent

  • amitriptyline l June 29, 2016

    amitriptyline l

    amitriptyline l

  • dangers of amiodarone June 29, 2016

    dangers of amiodarone

    dangers of amiodarone

  • what are the side effects of allopurinol June 29, 2016

    what are the side effects of allopurinol

    what are the side effects of allopurinol

  • medications to avoid with abilify June 29, 2016

    medications to avoid with abilify

    medications to avoid with abilify

  • zanaflex fosage for migrane June 29, 2016

    zanaflex fosage for migrane

    zanaflex fosage for migrane

  • oxytrol discontinued June 29, 2016

    oxytrol discontinued

    oxytrol discontinued

  • para que se usa la ciprofloxacin June 29, 2016

    para que se usa la ciprofloxacin

    para que se usa la ciprofloxacin

  • keflex usages June 29, 2016

    keflex usages

    keflex usages

  • cialis online purchase June 29, 2016

    cialis online purchase

    cialis online purchase

  • revatio vs viagra June 29, 2016

    revatio vs viagra

    revatio vs viagra

  • homemade sex on viagra June 29, 2016

    homemade sex on viagra

    homemade sex on viagra

  • augmentin amox clav June 29, 2016

    augmentin amox clav

    augmentin amox clav

  • viagra demonstration June 29, 2016

    viagra demonstration

    viagra demonstration

  • how to use viagra June 29, 2016

    how to use viagra

    how to use viagra

  • viagra dosages June 29, 2016

    viagra dosages

    viagra dosages

  • cialis savings card June 29, 2016

    cialis savings card

    cialis savings card

  • viagra substitute June 29, 2016

    viagra substitute

    viagra substitute

  • atorvastatin dosis June 29, 2016

    atorvastatin dosis

    atorvastatin dosis

  • better than viagra June 29, 2016

    better than viagra

    better than viagra

  • viagra on steroids June 29, 2016

    viagra on steroids

    viagra on steroids

  • cheapest viagra June 29, 2016

    cheapest viagra

    cheapest viagra

  • sildenafil teva June 29, 2016

    sildenafil teva

    sildenafil teva

  • viagra generics price June 29, 2016

    viagra generics price

    viagra generics price

  • tadalafil price June 29, 2016

    tadalafil price

    tadalafil price

  • liquid viagra June 29, 2016

    liquid viagra

    liquid viagra

  • levitra vs cialis June 29, 2016

    levitra vs cialis

    levitra vs cialis

  • side effects of viagra June 29, 2016

    side effects of viagra

    side effects of viagra

  • cheap viagra online June 29, 2016

    cheap viagra online

    cheap viagra online

  • viagra on line June 29, 2016

    viagra on line

    viagra on line

  • viagra boner mom June 29, 2016

    viagra boner mom

    viagra boner mom

  • female viagra pills June 29, 2016

    female viagra pills

    female viagra pills

  • levitra dosage June 29, 2016

    levitra dosage

    levitra dosage

  • generic cialis tadalafil June 29, 2016

    buy cialis tadalafil

    cialis online buy adobe clinic generic illustrator time trademarks forum – cialis online fast delivery france – cialis available in thailand

  • viagra without doctor prescription June 29, 2016

    how to take viagra for maximum effect

    viagra and alcohol use users browsing this forum – buy viagra in goa – 5mg viagra cost

  • tadalafil online June 29, 2016

    tadalafil 5mg

    cialis and alcoholic drinks forum rules – cialis and alcohol forum total posts – cialis online prescription forum contains new posts

  • viagra online canada pharmacy June 29, 2016

    viagra generic

    no prescription viagra – viagra in kuwait viagra – how quickly does viagra work

  • cialis over counter walmart June 29, 2016

    cialis at walmart

    cialis and alcohol announcements – cialis reviewed – cialis super active

  • levitra coupon June 29, 2016

    buy levitra

    levitra 5 mg daily – high street prescription levitra prices in uk – natural ed remedies