Home > Software engineering >  Nginx serving Angular returns 404
Nginx serving Angular returns 404

Time:05-13

I'm trying to run a production-built Angular app through nginx. Currently, I can serve the index.html just fine but the issue is for all the *.js and *css referenced as sources inside the index itself, those return a 404 error. I've been going back and forth between different configs using root or alias but none seem to do the trick.

First, I'm building the app using:

ng build --configuration production --aot

Note: The above command results in the creation of a dist folder with all the necessary files to run the app, I then move all those files to the path /apps/customer-ui

Folder structure is as follows:

/apps
  /customer-ui
    /index.html
    /(all other files resulting from build)

This is my nginx.conf

...

http {

    ...
    
    server {
        listen 80;
        server_name localhost;
        root /apps;
        index index.html;
        
        location / { }
        
        location ^~/customer-ui {
            alias /apps/customer-ui/;
            try_files $uri $uri/ /customer-ui/index.html =404;
        }
        
    }
}

Currently, accessing http://localhost/customer-ui returns the correct index but also the above mentioned 404s, because the references are pointing to http://localhost/filename.js instead of http://localhost/customer-ui/filename.js

Console errors here

Any help is very much appreciated.

CodePudding user response:

Since all the necessary files are inside customer-ui directory, it's better to point all paths there, like so:

        root /apps/customer-ui;
        index index.html;
        
        location / {
            try_files $uri $uri/ /index.html =404;
        }

Alternatively, you can use this (not recommended since it's rather confusing):

        root /apps;
        index index.html;
        
        location / {
            alias /apps/customer-ui/;
            try_files $uri $uri/ index.html =404;
        }
  • Related