5

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

8

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

  • 1
    don't do it hard way – Alexey Ten Jun 18 '15 at 5: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 9 '17 at 3:11
8

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/;
}
  • 1
    You should emphasize the latter slash, it's a big deal. Without it, does not work properly: serverfault.com/a/586614/262150 – Paulo Oliveira Mar 28 '16 at 22:47
  • 1
    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 5 '18 at 20:22

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.