17

I have one NGINX acting as reverse proxy. I need to remove a substring string_1 from the URL, the rest of the URL is variable.

Example:

Origin: http://host:port/string_1/string_X/command?xxxxx

Destination: http://internal_host:port/string_X/command?xxxxx

nginx.conf:

location /string_1/   { 

    proxy_pass  http://internal_host:port/$request_uri$query_string;

Thanks,

@pcamacho

Pedro
  • 607
  • 2
  • 9
  • 19

2 Answers2

19

It's really basic and simple. Just add /path/ part to proxy_pass and nginx will replace locations prefix with that path. You need to replace /string_1/ with /, so do it:

location /string_1/ {
    proxy_pass  http://internal_host:port/;
}
Alexey Ten
  • 7,922
  • 31
  • 35
  • 5
    You should emphasize the latter slash, it's a big deal. Without it, does not work properly: http://serverfault.com/a/586614/262150 – Paulo Oliveira Mar 28 '16 at 22:47
  • 4
    also notice that if the proxy_pass entry is using any other variable (like a variable for the hostname), nginx will stop adding the corrected `$uri`. You may workaround with a `rewrite ^/string_1(.*) $1 break;` and then use `proxy_pass http://$host/$uri;`. This `$uri` is the correct one, changed by the rewrite – higuita Mar 05 '18 at 20:22
15

I found the way to rewrite the proxy_pass URL:

  location  /string_1/   {  

    if ($request_uri ~* "/string_1/(.*)") { 
            proxy_pass  http://internal_host:port/$1;
    }   

  }

Regards,

@pcamacho

Pedro
  • 607
  • 2
  • 9
  • 19
  • 1
    don't do it hard way – Alexey Ten Jun 18 '15 at 05:22
  • 1
    This is actually better way. nginx does urldecoding for proxy_pass that just ends up /. Braindead, but that's how it works. This version however passes the url as-is, without decoding, which is correct and what would happen without a proxy. – user1338062 Dec 15 '15 at 13:06
  • After three hours of trial and error, your answer worked for me. Just what I needed. Thank you! – Bhargav Nanekalva May 09 '17 at 03:11
  • For whatever reason I have been having the hardest time getting my node-based server-side API application to set cookies for my React client-side application. I've tried setting *.domain.ext* for domain, for host (with *api.domain.ext* being the actual domain), tried leaving them out, they don't work - `document.cookie` is always empty. As soon as I used this method to proxy pass anything under *domain.ext/api/* to the Node app, cookies started working flawlessly with my React application. I'm going to link this answer in some of the other questions that are more specific to that. Thanks! – Rik Feb 04 '20 at 13:40