Setting up proxy_pass on nginx to make API calls t

2019-05-28 15:55发布

问题:

Problem:

I've set up a Lambda function behind API gateway which works beautifully. I have a hosted site that I want only a certain location to hit the API.

Example

https://www.example.com/ (Serves up html from hosted server)

https://www.example.com/foobar (Returns a JSON payload that is generated by Lambda and returned by AWS)

Here is my server block:

   location = /foobar {
            proxy_pass     https://someawsuri;
            proxy_redirect default;
    }

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
    }

I've tried reviewing the docs and read multiple SO posts, but I haven't been able to do what I want. Everything that I've tried has produced the error 502 Bad Gateway.

Question:

How do I configure nginx to make a request to API gateway?

Thanks.

回答1:

I think you need those two lines:

proxy_set_header Host "XXXXXX.execute-api.REGION.amazonaws.com";
proxy_ssl_server_name on;

Here is the explanation about the why:

The HOST header is required as is described here

The Amazon API Gateway endpoint. This value must be one of the region-dependent endpoints listed under Regions and Endpoints. In the US East (N. Virginia) region, it is apigateway.us-east-1.amazonaws.com.

The proxy_ssl_server_name on;

Enables passing of the server name through TLS Server Name Indication extension (SNI) when establishing a connection with the proxied HTTPS server.