nginxlocationsites

Nginx location - sites configuration not working


i have an nginx running with a location :

location / {
   proxy_pass http://10.22.1.27:3000;
               proxy_http_version 1.1;
               proxy_set_header Connection "";
}

as a result my application comes up

when I change the location to

location /login {
     proxy_pass http://10.22.1.27:3000;
     proxy_http_version 1.1;
     proxy_set_header Connection "";
    
}

My application is not coming up at all. In the console I get the following error message :

ET https://demo3.xxxxx.rocks/static/js/vendor.f9538d6f661cb0e94054.js net::ERR_ABORTED 404 (Not Found)

Any idea what I am doing wrong


Solution

  • A location tells NGINX how to handle requests when the path matches the given pattern.

    location / will match any path, or more precisely, anything starting with /, which is effectively any request. So that already includes /login and any other page or path you navigate to.

    When you changed it to location /login, it would no longer match / when you first navigated to the address, which would cause HTTP 404 Not Found.

    I know you haven't used this but just to make the point, note that location / is different from location = /, because the second case would only match if the path is exactly /, so it would no longer match /login.

    Bottom line: leave it as location / unless you have specific needs to handle different paths in different ways. For example, you might handle requests at /api/... with a proxy_pass to a backend, but /docs/... requests by serving static files from a local directory.

    EDIT: Also, if you do change the location path, bear in mind it will append that to the proxy_pass address. So a request to /login/foo will be forwarded to http://10.22.1.27:3000/login/foo. If the upstream server doesn't recognise the /login path then that will fail with 404 Not Found.

    To fix that, add a path to your proxy_pass, even if it is just a root path, for example http://10.22.1.27:3000/ (note the trailing slash). Then NGINX will map the location path to the proxy_pass path, and only append what's left. For example, now a request to /login/foo will be forwarded to http://10.22.1.27:3000/foo.