Score:0

Why nginx "return 301" and ”try_files“ fall into an infinite loop

dk flag

my conf code:

index index.html index.php;
location / {
    if ($uri = '/a/') {
        return 301 https://example.com/a;
    }
    try_files $uri $uri/ =404; 
}

If url is /a/, 301 to /a, then try_files part, add / to /a end, become /a/.

Next step, I think it will try the index definition, become /a/index.html, and reach the file.

But actually, It tried /a/, and jump out the location, then goes into location again, to if ($uri = '/a/') { ... }.

Then an infinite loop.

Why, I just got confused.


What I want to do is

  1. If request example.com/a/, jump to example.com/a, then to 2
  2. If request example.com/a, show example.com/a/index.html (but url is example.com/a).

Anyone can help me to reach this?

Score:2
cz flag

It's doing exactly what it's meant to do.

You can never reach /a/index.html because you keep redirecting back to /a before this can possibly happen. When nginx processes this, it sees the directory on the filesystem and automatically redirects (correctly) to /a/.

You should remove this inappropriate redirect.

dk flag
Did you mean when try`$uri/`, first `/a/` then `/a/indx.html`? (and `/a/` fires re-enter `location` back to `/a`.)
digijay avatar
mx flag
Yes, that's what your 301 redirect tells your nginx to do
Michael Hampton avatar
cz flag
@nanxiaobei You never got to try_files because if is processed first. And **you cannot strip the trailing slash when serving static content**. It is mandatory. Stop trying.
dk flag
@MichaelHampton Thanks. The nginx error shown was "infinite loop", so I think first `if`, then `$uri/`, then back to `if` - so as a loop. When `if` processed, changed to `/a`, so must be `/a/` again it'll back into `if`.
Score:0
sv flag

Welcome to ServerFault. You can do what's mentioned in the OP with the following code...

location / {
    if ($uri = '/a/') {
        return 301 https://example.com/a;
    }
    try_files $uri $uri/index.html =404; 
}

Please see the relevant question and accepted answer at Removing the trailing slash from a URL with nginx .

Basically, we don't have to rely on index and rather serve index.html directly when example.com/a is requested.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.