mediocre
mediocre

Reputation: 564

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!

Upvotes: 3

Views: 7019

Answers (2)

Wicfasho
Wicfasho

Reputation: 331

You can still retain your Nginx config code with the '/' (forward slash) and use example.com/admin/test to access test route.

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

Upvotes: 0

Ry-
Ry-

Reputation: 225281

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;
    …
}

Upvotes: 10

Related Questions