Search code examples
perlnginxmojolicious

How can I strip the base url in Nginx for a Mojolicious app?


I am trying to run a Mojolicious up as a reverse proxy. My Nginx configuration looks like this:

upstream printo {
    server 127.0.0.1:3000;
}

[..]

location /print {
   proxy_pass http://printo;
   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection "upgrade";
   proxy_set_header Host $host;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_set_header X-Forwarded-Proto $scheme;
}

I'd like to strip the /printo portion of the URL before the request reaches the Mojolicious app - otherwise, all the requests have a /printo/something URL, which results in a 404.

I've seen this but I'd like to do it in Nginx if possible.

I've tried rewrite like this:

rewrite ^/print/(.+)$ $1;

to no result.

How's that done?


Solution

  • To modify the URI as it passes upstream, you can use a rewrite...break or perform a similar function using the proxy_pass directive itself.

    For example:

    location /print {
        rewrite ^/print(/.*)$ $1 break;
        proxy_pass http://printo;
        ...
    }
    

    Remember to keep a leading / in the rewritten URI. See this document for details. Or:

    location /print/ {
        proxy_pass http://printo/;
        ...
    }
    

    The location value should have a trailing / to ensure that the text substitution occurs correctly. See this document for details.