Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure nginx proxy_pass with two parallel locations

Tags:

nginx

Let's say we have the following quite minimal nginx.conf:

server {
  listen 443 default ssl;

  location /api/v1 {
    proxy_pass http://127.0.0.1:8080;
  }
}

Now, I'm trying to use nginx itself as an event-source. Another component in my system should be aware of any HTTP requests coming in, while ideally not blocking the traffic on this first proxy_pass directive.

Is there any possibility to have a second proxy_pass which "just" forwards the HTTP request to another component as well while completely ignoring the result of that forwarded request?

Edit: To state the requirement more clearly: What I want to achieve is that the same HTTP requests are sent to two different backend servers, only one of them really handling the connection in terms of nginx. The other should just be an "event ping" to notify the other service that there has been a request.

like image 814
markusthoemmes Avatar asked Oct 22 '16 10:10

markusthoemmes


1 Answers

This can be done using echo_location directive (or similar, browse the directives) of the 3rd party Nginx Echo Module. You will need to compile Nginx with this module or use Openresty which is Nginx bundled with useful stuff such as this.

Outline code:

server {
    [...]

    location /main {
        echo_location /sub;
        proxy_pass http://main.server:PORT;
    }
    location /sub {
        internal;
        proxy_pass http://alt.server:PORT;
    }
}

There is also the now undocumented post_action directive which does not require a third party module:

server {
    [...]

    location /main {
        proxy_pass http://main.server:PORT;
        post_action @sub;
    }
    location @sub {
        proxy_pass http://alt.server:PORT;
    }
}

This will fire a subrequest after the main request is completed. Here is an old answer where I recommended the use of this: NGinx - Count requests for a particular URL pattern.

However, this directive has been removed from the Nginx documentation and further usage of this is now a case of caveat emptor. Four years on from 2012 when I gave that answer, I wouldn't recommend using this.

like image 91
Dayo Avatar answered Nov 15 '22 11:11

Dayo