Casper Liao
Casper Liao

Reputation: 33

What's wrong with Nginx location match rule

I do read the Nginx documentation about location matching. I know about the prioriy of modifier.

And here is my config.

    location = /login {
        root  /usr/share/nginx/mysite;
        try_files $uri /index.html;
    }

    location = / {
        root  /usr/share/nginx/mysite;
        try_files $uri /index.html;
    }

    location ~ /(.*) {
        proxy_pass http://127.0.0.1:8080/$1;
    }

What I want is when I type "http://example.com/" "http://example.com/login" , the request will goes index.html which is a React App , and other request will goes proxy pass to my Tomcat application which is bind 8080 port.

But "http://example.com/" "http://example.com/login" request goes proxy_pass , what?

According to Nginx documentation, the "=" modifier is "Priority one" I expect it is an exact match.

If an exact match is found, the search terminates

I also use https://nginx.viraptor.info/ test for it.

It shows what I expected.

But it looks like the running server not act what Nginx doc said.

Any ideas?

Upvotes: 3

Views: 737

Answers (1)

Richard Smith
Richard Smith

Reputation: 49672

The last parameter of a try_files statement is special. It can be a status code, a named location, or the URI of an internal redirect. See this document for details.

In your current configuration, Nginx generates an internal redirection to /index.html and restarts the search for a matching location. So the /index.html request is sent to the proxy_pass.

Place /index.html before the last parameter so that it's interpreted as a file parameter and is processed within the same location block. The $uri is unnecessary in this particular case.

For example:

root  /usr/share/nginx/mysite;

location = /login {
    try_files /index.html =404;
}
location = / {
    try_files /index.html =404;
}
location / {
    proxy_pass http://127.0.0.1:8080;
}

The =404 will never be reached. The final location can be simplified and the capture is unnecessary.

Upvotes: 2

Related Questions