Rewrite Nginx location

Hello Folks,

I am setting up Nginx on EC2 and reverse proxying to a bunch of microservices that are behind ALB. Since AWS ALB IPs change every 60 seconds and are sometimes random. I am occasionally seeing upstream timeouts in error logs. Based on a few google searches, Nginx doesn't support the dynamic resolution and it's only supported in the commercial version. I have been trying to implement this solution from [article](https://medium.com/driven-by-code/dynamic-dns-resolution-in-nginx-22133c22e3ab). But running to URI issues.

`location /foo/`

`set $backend "`[`www.example.com`](https://www.example.com)`";`

`proxy_pass $backend;`

The problem with the above block is the downstream services getting "foo" in the request, But I need to strip it. I have tried a few things but couldn't get it working. can someone please help me out?

Edit 1:

If anyone ended up having the same question, This is the final config that worked for me. This strips whatever is the first string between // and passes the rest to the service. I have multiple location paths, Instead of having multi rewrites, I am thinking to go with a single rule outside a location block but couldn't make it work.

`location /foo/`

`set $backend "`[`www.example.com`](https://www.example.com)`";`

`rewrite ^/.*?(/.*)$ $1 break;`

`proxy_pass $backend;`

1 thought on “Rewrite Nginx location”

  1. You could probably make it work with some proxy_pass muckery, but you can also do it this way. Rewrite the url inside the matched location with the break flag:

    location /foo/ {
    rewrite ^/foo/(.*) /$1 break;
    set $backend “www.example.com”;
    proxy_pass $backend;
    }

    Reply

Leave a Comment