23

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

2 Answers 2

24

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/; } 
2
  • 7
    You should emphasize the latter slash, it's a big deal. Without it, does not work properly: serverfault.com/a/586614/262150 Commented Mar 28, 2016 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 Commented Mar 5, 2018 at 20:22
17

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

4
  • 1
    don't do it hard way Commented Jun 18, 2015 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. Commented Dec 15, 2015 at 13:06
  • After three hours of trial and error, your answer worked for me. Just what I needed. Thank you! Commented May 9, 2017 at 3: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! Commented Feb 4, 2020 at 13:40

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.