Score:1

nginx: make internal redirect to a different `location` block

cn flag

try_files' signature is try_files file ... uri;, so one usually uses it to perform tasks like serve file1 if it exists otherwise serve file2 if it exists otherwise pass the decision to a different location block (the one for the mentioned uri).

Can I somehow use the last part only? That means, do not try to serve any files, just pass the request to a different location block. The simple idea of not mentioning any files fails with nginx: [emerg] invalid number of arguments in "try_files" directive.

A workaround is to write try_files /does/not/exist.html /some/uri; but it looks ugly and possibly incurs a penalty for checking the existence of the nonexistent file.

For context, why do I need this?

I have a config like

location /path/ {
    try_files $uri $uri/index.html =404;
    alias /some/dir/;
    expires 604800;
}

This unfortunately doesn't match /path (no trailing /). One could simply write location /path, but it is said to cause path traversals.

My idea is to add one more handler like

location = /path {
  <do the same as for /path/>
}

I could of course copy the alias and try_files there, but that way I would also have to copy the expires directive and possible others and keep them synced.

Richard Smith avatar
jp flag
You could use `rewrite ^ /path/ last;`
Score:0
by flag

Yes, rewrite is good here, just add a block location /path and use rewrite to redirect the request to the /path/ block, like this

location = /path {
    rewrite ^ /path/ last;
}

location /path/ {
    try_files $uri $uri/index.html =404;
    alias /some/dir/;
    expires 604800;
}
I sit in a Tesla and translated this thread with Ai:

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.