Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve Express.JS app from subfolder

I use nginx to serve a static html site and a expressjs app under the same domain. My nginx config looks like this:

    location / {
            try_files $uri $uri/ /index.html;
            autoindex  off;
            root /var/www/example.com/static/;
    }

    location /admin {
            proxy_pass http://localhost:3007/;
            proxy_set_header Host $host;
            proxy_buffering off;
            autoindex  off;
    }

I'm able to access my app running on port 3007 if i access example.com/admin so it seems that my app.get('/', routes.index); is working but I'm having some troubles getting my other routes to work.

For example:

app.get('/admin/test', function(req, res) {
    console.log("test!")
});

If I try to access example.com/admin/test I'll just see Cannot GET //test and a 404 according to my logs:

GET //test 404 11ms

If I change the route to /test it's the same problem. Any pointers what's wrong there. I haven't found a way to make routes relative to the base path they are mounted to (/admin).

Thanks!

like image 437
mediocre Avatar asked Jun 26 '26 21:06

mediocre


1 Answers

Mind the slash:

location /admin {
    proxy_pass http://localhost:3007/; # here
    …
}

If you remove it, the real request URI will be proxied.

You can also remove the /admin part with Nginx:

location ~ ^/admin($|/.*$) {
    proxy_pass http://localhost:3007$1;
    …
}
like image 153
Ry- Avatar answered Jun 29 '26 15:06

Ry-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!