Nginx 404 error with existing urls Angular 2 One page application with routing

February 14, 2017 4.2k views
Nginx Ubuntu 16.04

I have a one-page angular 2 application that uses routing. When I hit my base URL example.com then the page loads correctly. However example.com/dashboard results in a 404 error.

My server logs have this:

2017/02/14 05:37:22 [warn] 680#680: conflicting server name "example.com" on 0.0.0.0:80, ignored
2017/02/14 05:37:22 [warn] 680#680: conflicting server name "www.example.com" on 0.0.0.0:80, ignored
2017/02/14 05:37:22 [warn] 680#680: conflicting server name "example.com" on [::]:80, ignored
2017/02/14 05:37:22 [warn] 680#680: conflicting server name "www.example.com" on [::]:80, ignored
2017/02/14 05:48:43 [error] 997#997: *1 open() "/var/www/example.com/html/dashboard" failed (2: No such file or directory), client: 41.180.12.42, server: example.com, request: "GET /dashboard HTTP/1.1", host: "example.com"
2017/02/14 05:49:03 [error] 997#997: *1 open() "/var/www/example.com/html/dashboard" failed (2: No such file or directory), client: 41.180.12.42, server: example.com, request: "GET /dashboard HTTP/1.1", host: "example.com"

The page dashboard.html does not exist because its I'm using angular's routing and I built the application using webpack.

Here is my server block:

server {
        listen 80;
        listen [::]:80;

        root /var/www/example.com/html;

    index index.html index.htm index.nginx-debian.html;

        server_name example.com www.example.com;

        location / {
            try_files $uri $uri/ =404;
         }
}

Thank you for your help.

2 Answers
jtittle1 February 14, 2017
Accepted Answer

@marcduplessis1

Instead of using:

try_files $uri $uri/ =404;

... try using:

try_files $uri $uri/ /index.html;

This assumes that Angular is setup to handle requests that are sent to index.html and will route all requests accordingly.

@jtittle Thank you for the help! that worked :)

  • @marcduplessis1

    No problem at all, happy to help!

    The reason =404 doesn't work is because of what that line is saying. First NGINX will check to see if $uri is valid, if not then it checks with a / -- if neither a valid, it defaults to a 404 as the resource isn't valid (i.e. a valid file or directory). If it were, you'd still get a 404, but if you placed and index.html file in there, it'd then be valid.

    With the above, /index.html, we just force Angular to handle the request.

    • @jtittle
      Oh! I see that makes complete sense now. Now, any page that doesn't match the URL is handled by my custom 404-page handle in angular.

      • I have tried your solution with my project and its still not working. I can go to the main site but i cant navigate to other routes because it gives me 404 error. Please I need help

    • I have used your solution but mine did not work. Is there an alternative?

Have another answer? Share your knowledge.