Why is simple NGINX exact location match failing?

Viewed 40

I'm trying to use NGINX to route requests with no path (e.g. http://example.com/ or http://example.com) to a particular html file using this config (this is just the relevant section in the server config):

root $root;

location = / {
    index index.html;
    alias $root/apps/www/html/main/;
}

If I navigate to the site with just the root url (http://example.com) I would expect NGINX to return <root>/apps/www/html/main/index.html but instead it ignores the exact location and goes directly to the root: all requests come back with the error that <root>/index.html cannot be found.

To try to debug this I've tried using different exact location paths (e.g. location = /foo) but those are ignored as well. Also I've tried using root instead of alias, but no success there either.

How do you reroute to a specific location in NGINX?

1 Answers

The index module will internally rewrite the URI to /index.html then restart the search for a matching location.

So you either need to provide a location = /index.html block to match the new URI.

Or you can process the entire request in a single location block by bypassing the index module and using try_files instead.

For example:

location = / {
    try_files /apps/www/html/main/index.html =404;
}

See this document for details.

Related