Score:0

Nginx locations configuration

br flag
Vv.

I have config

location ~ \.(pdf)$ {
    expires 2h;
}

location / {
    ...backend rules...
}

Now I want the first block to be executed only for really existing pdfs, otherwise the request would be passed to the backend. I suppose I should add in the first location block try_files $uri @backend:

location ~ \.(pdf)$ {
    try_files $uri @backend;
    expires 2h;
}

location / {
    ...backend rules...
}

location @backend {
    ...same backend rules...
}

But it turns out that both locations / and @backend will be absolutely identical, is there any way to combine them or should I just make two identical blocks?

br flag
Put backend rules to separate file and use `include`.
br flag
Vv.
A separate file is an idea, but I don't want to add complexity with an additional file. Is there a more elegant way?
Score:0
gr flag

As a workaround, you can shorten your location to

location / {
    try_files "" @backend;
}

This will produce an extra system stat call for every request, but since it is your web root directory that will be stat'ed, those calls should be some kind of cached by the kernel and it should not be a serious performance impact.

PS

You don't need a capture group for your regex location, just location ~ \.pdf$ { ... } will be enough (yet slightly more performant).

Update

One more suggestion that would allow to reduce the number of locations:

map $uri $try {
    ~\.pdf$                                 $uri;
    <some_other_mask_to_try_locally_first>  $uri;
    # default value will be an empty string
}
server {
    ...
    location / {
        try_files $try @backend;
    }
    location @backend {
        ...
    }
}
br flag
Vv.
Thanks for the ideas here and on SO. On the brackets - of course, while simplifying the config for the question I forgot to remove them)
Ivan Shatsky avatar
gr flag
Check the answer update.
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.