2

My nginx configuration is not working as expected. This is my location config in nginx.conf:

 location / {
            proxy_pass "https://localhost:9002";

        }

        location /app  { 

            root /usr/local/var/www;
            index index.html;
            # autoindex off;
            try_files $uri /index.html;

         }
  • When I am doing /app/some-url its opening http://localhost:9002. I expect it should load my static site

  • When I comment location / block then it works fine and opens static site.

2 Answers2

2

with the root directive, the pathname of a static resource is calculated by concatenating the root value with the URI. In your case, the URI /app/foo.css is expected to be located at /usr/local/var/www/app/foo.css. Notice that app is a subdirectory within the www directory. See this document for details.

The last term of a try_files directive is a URI, error code or named location. The URIs of your static application begin with /app, so the default URI should probably be /app/index.html to locate the correct file. See this document for details.

For reasons of simplicity and efficiency, the best solution is to move all of your files into a directory with the same name as the URI prefix (e.g. app).

For example:

/usr/local/var/www/app/index.html
/usr/local/var/www/app/foo.js
/usr/local/var/www/app/foo.css

The Nginx configuration would look like:

location /app {
    root /usr/local/var/www;
    index index.html;

    try_files $uri $uri/ /app/index.html;
}

If the directory containing the static application, is not the same as the URI prefix used to access it, you will need to use an alias directive or other tricks to rewrite the URIs so that root will work. See this document for details.

For example:

/usr/local/var/www/index.html
/usr/local/var/www/foo.js
/usr/local/var/www/foo.css

The Nginx configuration would look like:

location /app {
    alias /usr/local/var/www;
    index index.html;

    if (!-e $request_filename) { rewrite ^ /app/index.html last; }
}

The location and alias values should both end with a / or neither end with a /. Avoid using alias and try_files together, due to this long term issue. See this caution on the use of if.

Richard Smith
  • 12,834
  • 2
  • 21
  • 29
-1

Move the location /app above location / otherwise / takes precedence and location /app is ignored.