3

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!

2 Answers 2

11

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;
    …
}
Sign up to request clarification or add additional context in comments.

4 Comments

Sometimes it's the little things that count most. Removing the slash did the track. Thanks for the fast (Almost too fast, I'll have to wait a couple of minutes before it's possible to accept it ;) ) reply!
Couldn't writing it as /admin/? do the same thing? I'm looking to do the same thing and wondering if this would also work.
@Bill: The ($|/.*$) isn’t so much to allow an optional / (I think Nginx does this anyways) as to capture the part of the path after /admin so it can be given to proxy_pass (see the $1 at the end). proxy_pass http://localhost:3007 would result in the /admin being passed too.
Oh, okay. Thank you for clarifying. I appreciate the quick response to this pretty old question too.
0

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!")
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.