简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM