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

  • paid essay writing June 29, 2016

    writing a descriptive essay https://onlinecasinos4me.com/

  • ivermectin pills for humans June 29, 2016

    ivermectin pills for humans

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • ivermectin dosage for pigs June 29, 2016

    ivermectin dosage for pigs

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • my essay writing June 29, 2016

    writing experience essay https://essaypoints.com/

  • ivermectin 1.87 dosage for humans June 29, 2016

    ivermectin 1.87 dosage for humans

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • what to write about for college essay June 29, 2016

    write an essay introduction https://essaytag.com/

  • ivermectin 3mg tablets June 29, 2016

    ivermectin 3mg tablets

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • ivermectin for rabbits mites June 29, 2016

    ivermectin for rabbits mites

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • ivermectin protocol June 29, 2016

    ivermectin protocol

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • ivermectin dosage for cattle June 29, 2016

    ivermectin dosage for cattle

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • writing argument essay June 29, 2016

    essay writing service usa https://essayghostwriter.com/

  • paid to write essays June 29, 2016

    writing compare and contrast essay https://essaywritercentral.com/

  • cymbalta and high blood pressure June 29, 2016

    cymbalta and high blood pressure

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • 1 June 29, 2016

    1

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • escitalopram pill f 5 6 June 29, 2016

    escitalopram pill f 5 6

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • zoloft side effects weight loss June 29, 2016

    zoloft side effects weight loss

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • does lipitor cause hair loss June 29, 2016

    does lipitor cause hair loss

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • hydrochlorothiazide dosing June 29, 2016

    hydrochlorothiazide dosing

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • cymbalta and phentermine June 29, 2016

    cymbalta and phentermine

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • gay dating games porn June 29, 2016

    gay dating game on steam https://gaydatinglosangeles.com/

  • what is the difference between gabapentin and lyrica June 29, 2016

    what is the difference between gabapentin and lyrica

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • lexapro coupon June 29, 2016

    lexapro coupon

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • gay chat dating site June 29, 2016

    a4a gay dating https://datinggayservices.com/

  • gay dating where June 29, 2016

    gay russian dating sites https://gayedating.com/

  • best gay catholic dating site June 29, 2016

    gay men dating https://gayonlinedating.net/

  • free dating site for gay guys June 29, 2016

    good gay dating sims https://gay-singles-dating.com/

  • black male gay dating service June 29, 2016

    gay dating site guide https://dating-gaym.com/

  • quetiapine fumarate and alcohol June 29, 2016

    quetiapine fumarate and alcohol

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • fluoxetine 10mg tablet June 29, 2016

    fluoxetine 10mg tablet

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • how long does omeprazole take to work June 29, 2016

    how long does omeprazole take to work

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • gemfibrozil and atorvastatin June 29, 2016

    gemfibrozil and atorvastatin

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • norvasc insomnia June 29, 2016

    norvasc insomnia

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • losartan potassium hydrochlorothiazide side effects June 29, 2016

    losartan potassium hydrochlorothiazide side effects

    How To: HTTP redirects with API Gateway and Lambda – RyanG Blog

  • gay men dating new york June 29, 2016

    bombay gay dating site https://gaychatus.com/

  • gay dating fort myers florida June 29, 2016

    gay dating bbc stories https://gaychatgay.com/

  • gay guy dating sites June 29, 2016

    dating sites for gay geeks https://freegaychatnew.com/

  • dating a older gay men points June 29, 2016

    gay guy dating amanda https://gaychatrooms.org/

  • keto chocolate cookies June 29, 2016

    keto advanced

  • dating chat sites free June 29, 2016

    free online dating in buffalo ny

  • 100 free dating sites with no credit card required June 29, 2016

    free messaging dating sites

  • diclofenac injection June 29, 2016

    diclofenac injection

    diclofenac injection

  • how viagra works June 29, 2016

    how viagra works

    how viagra works

  • cialis 20mg cost June 29, 2016

    cialis 20mg cost

    cialis 20mg cost

  • non prescription viagra June 29, 2016

    non prescription viagra

    non prescription viagra

  • tadalafil research powder June 29, 2016

    tadalafil research powder

    tadalafil research powder

  • ivermectin for covid June 29, 2016

    stromectol dosing

    stromectol dose

  • viagra price walmart June 29, 2016

    viagra price walmart

    viagra price walmart

  • is cialis safe June 29, 2016

    is cialis safe

    is cialis safe

  • sildenafil cream June 29, 2016

    sildenafil cream

    sildenafil cream

  • cialis wikipedia June 29, 2016

    cialis wikipedia

    cialis wikipedia

  • tadalafil 20 mg June 29, 2016

    cialis otc

    cialis over counter walmart

  • fildena sildenafil citrate June 29, 2016

    order fildena online

    fildena purple pill

  • online viagra pills June 29, 2016

    online viagra pills

    online viagra pills

  • cialis at costco June 29, 2016

    cialis at costco

    cialis at costco

  • stromectol scabies treatment June 29, 2016

    stromectol ose per kg

    buy stromectol online usa

  • cialis ingredients June 29, 2016

    liquid tadalafil

    cialis us pharmacy – more testostrone than cialis – order generic cialis pills online

  • cialis canada without prescription June 29, 2016

    cialis without dr prescription pharmacy

    cialis without a doctor prescription usa

  • ivermectin over the counter June 29, 2016

    stromectol 3 mg tablet

    stromectol 12mg online

  • acheter viagra 100mg pfizer June 29, 2016

    acheter viagra 100mg pfizer

    acheter viagra 100mg pfizer

  • achat viagra canada June 29, 2016

    achat viagra canada

    achat viagra canada

  • viagra generic name south africa June 29, 2016

    viagra generic name south africa

    viagra generic name south africa

  • teva viagra generic June 29, 2016

    teva viagra generic

    teva viagra generic

  • where to buy generic cialis in canada June 29, 2016

    where to buy generic cialis in canada

    where to buy generic cialis in canada

  • viagra jokes australia June 29, 2016

    viagra jokes australia

    viagra jokes australia

  • comprar viagra 200 india June 29, 2016

    comprar viagra 200 india

    comprar viagra 200 india

  • buy cialis india pharmacy June 29, 2016

    buy cialis india pharmacy

    buy cialis india pharmacy

  • comprar cialis 10mg paypal June 29, 2016

    comprar cialis 10mg paypal

    comprar cialis 10mg paypal

  • viagra on steroids singapore June 29, 2016

    viagra on steroids singapore

    viagra on steroids singapore

  • buy sildenafil online usa June 29, 2016

    buy sildenafil online usa

    buy sildenafil online usa

  • 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