Nginx forward all requests to another domain

nginx

I have been struggling to get this whole setup to work. I've found bits and pieces on the net but nothing that solves all of my requirements. I need to do this to make IE8 work, so unfortunately my hands are tied a little. I can move some endpoints around, but probably not too much.

I have a users api which sits at https://api.foo.com/1.0/users. That endpoint accepts all request types along with parameters, and dynamic segments. Below are some samples

I want to configure nginx to accept requests from another domain and path and seamlessly forward them to those endpoints. For example

In order to accomplish this, I need request parameters as well as form data to be forwarded. Basically the whole request needs to be forwarded in tact and then return. Also note that I have a couple of different subdomains so awesome is but one of a couple of names I want to change.

The pattern is this

http://example.com/api/<subdomain>/<details> -> https://<subdomain>.foo.com/1.0/<details>

My biggest struggle is keeping the exactly the same, along with passing different kinds of requests.

my efforts
I've tried a number of things, but probably the closest I've got to is this

location ~ ^/api/(.*)/(*.) { 
    resolver 8.8.8.8;
    proxy_pass https://$1.foo.com/1.0/$2$is_args$args;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    #proxy_set_header X-Host $host;
}

**The `X-Host` directive doesn't work for me hence the comment

This works for the first two cases, but not the third. Also, I haven't got the POST request to work with this. Mostly I get 502 Bad Gateway errors. It seems to me that the doesn't map completely instead it cuts off at the first '/' it receives. Adding another location directive with 3 regex params also hasn't helped me.

I'd really appreciate any help on this topic as I'm totally stuck as to what to do next.

Best Answer

Your regex is incorrect, you sould use location ~ ^/api/([^/]+)/(.*)$ instead because I don't see how the PCRE lib can choose $1 as the subdomain, its content will likely be awesome/users instead of awesome.

Related Topic