Nginx rewrite+redirect to different port on url path

The usage is very typical. Say you have an app that’s listening on port 1234. You want to direct all urls look like /myapp, /myapp, /myapp/* to be handled by port 1234. This need to be transparent for client, so that the port number is not shown on browser.

In the end here’s the server block:

[code]

server { listen 80; location /lgg { rewrite_log on; rewrite ^/lgg$ /lgg/ redirect; rewrite /lgg(.*) $1 break; proxy_pass http://127.0.0.1:14407; } }

[/code]

It doesn’t look complicated at all. But a few points to take note:

  • The break directive is needed. This makes nginx continue processing within the block instead of breaking out of location and look for new location block match. This is exact opposite to intuition - break means do not break and continue
  • /lgg is problematic because on myapp running on port 1234, links are using relative url. So if we have /lgg/, it will be ./js/a.js, and it will resolve to /lgg/js/a.js. On the other hand, if it's /lgg, it will be resolved to /js/a.js, parallel to current page. Now this resolving happens entirely on client side. To accommodate for that, we use a rewrite with "redirect" to 301 redirect. Url is changed too
Written on June 19, 2017