Site icon Voina Blog (a tech warrior's blog)

#nginx proxy_pass an URI to another server with a different URI

Advertisements

Nginx can be used very nicely to aggregate resources after the same fronted by using it as a proxy.

I want my set-up to be like:
URL1: https://blog.voina.org -> nas1 hosted wordpress
URL2: https://blog.voina.org/store -> nas2 hosted store with URL https://nas/store
URL3: https://blog.voina.org/doc -> nas4 hosted wiki with URL https://nas4/wiki

How can we do this using location and proxy_pass directives in nginx ? There is a nice post in the nginx wiki but was still confusing to me without examples.

URL1:
This is the default case all requests are directed to the wordpress on the local nas1 machine where nginx runs.

URL2:
This is the simple case:

location /store/ {
   proxy_pass https://nas2;
}

In this case the full URI that is matched by the rule will be passed as it is to the proxy_pass directive.
So https://blog.voina.org/store/cart –> https://nas2/store/cart

URL3:
This is the most complicated case. Here we have a redirection (with a regex) but also an URI change.
We try first:

location ~ ^/docs/.*$ {
   rewrite ^/docs/(.*)  /wiki/$1 break;
   proxy_pass http://nas4;
}

In this case the same as in case of URI2, the URI that is matched by the rule will be passed as it is to the proxy_pass directive.
This means that using this rule we have:
https://blog.voina.org/docs/index –> https://nas4/docs/index

But this is not OK for us, so we need a rewrite rule to replace the client called URI with the URI front on our nas4 machine.

rewrite ^/docs/(.*)  /wiki/$1 break;

Putting all together we have:

location ~ ^/docs/.*$ {
   rewrite ^/docs/(.*)  /wiki/$1 break;
   proxy_pass http://nas4;
}

This means that using the final rule we have:
https://blog.voina.org/docs/index –> https://nas4/wiki/index

Exit mobile version