Nginx subpath routing issue with Angular 2 application

Updated: Feb 19, 2025

Nginx subpath routing issue with Angular 2 application

When working with an Angular 2 application and Nginx as a reverse proxy server, you might encounter an issue with serving static files from a subpath. This issue can be caused by incorrect Nginx configuration. In this answer, we will discuss the possible causes and solutions for this problem.

First, let's understand the Angular 2 application structure. By default, an Angular 2 application is built with index.html as the entry point, and all the application files are served under the /dist folder. The index.html file is responsible for loading the main application bundle, which is located at /dist/<project-name>/<version>/index.html.

Now, let's discuss the Nginx configuration issue. When you try to serve static files from a subpath, Nginx might not be able to find the files because it is looking for them in the wrong place. To fix this issue, you need to configure Nginx to serve the static files from the correct location.

Here's an example of a correct Nginx configuration for serving an Angular 2 application from the /var/www/html/myapp directory and serving static files from the /var/www/html/myapp/dist directory:

server {
    listen 80;
    server_name example.com www.example.com;

    location / {
        root /var/www/html/myapp;
        index index.html;
        try_files $uri $uri/ /index.html;
    }

    location /dist {
        alias /var/www/html/myapp/dist;
        expires max;
    }
}

In the above configuration, the / location block serves the index.html file from the /var/www/html/myapp directory, and the try_files directive is used to check if the requested file exists in the current location before falling back to the index.html file. The /dist location block serves the static files from the /var/www/html/myapp/dist directory.

If you still encounter issues with serving static files from a subpath, you can try the following solutions:

  1. Make sure that the dist folder is included in the Git repository and is deployed to the server along with the application code.
  2. Check if the Nginx user has the necessary permissions to access the dist folder.
  3. Try using the root directive instead of the alias directive in the /dist location block.
  4. If you are using Angular CLI, try building the application with the --base flag set to the subpath you want to use. For example, ng build --base /myapp/.
  5. Check if there are any conflicting configurations in the Nginx configuration file.

By following the above solutions, you should be able to resolve the Nginx subpath routing issue with your Angular 2 application.