0

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?

2 Answers2

2

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.

Michael Hampton
  • 244,070
  • 43
  • 506
  • 972
  • Did you mean when try`$uri/`, first `/a/` then `/a/indx.html`? (and `/a/` fires re-enter `location` back to `/a`.) – nanxiaobei Jul 31 '21 at 11:15
  • Yes, that's what your 301 redirect tells your nginx to do – digijay Jul 31 '21 at 11:47
  • @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. – Michael Hampton Jul 31 '21 at 11:49
  • @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`. – nanxiaobei Aug 01 '21 at 13:51
0

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.

Pothi Kalimuthu
  • 6,117
  • 2
  • 26
  • 38