49

I've encountered a few questions and answers on here that use this syntax:

location @default {
  # ...
}

location /somewhere {
    try_files $uri @default;
}

I've searched high and low on the Googles and I can't seem to find any documentation of it. What does it mean and what are some of it's practical uses? Is it some sort of variable declaration and assignment? Sorry for the newbie question.

0

2 Answers 2

25

The answer is in official documentation.

The “@” prefix defines a named location. Such a location is not used for a regular request processing, but instead used for request redirection. They cannot be nested, and cannot contain nested locations.

2
  • 64
    As explanation goes, this says absolutely nothing. Sep 1, 2016 at 10:59
  • So this isn't particularly different to having a normal block with internal in it?
    – James
    Mar 30, 2017 at 14:04
49

In the example that you quote in your question:

location @default {
  # ...
}

location /somewhere {
  try_files $uri @default;
}

If the incoming request is received at http://your-domain/somewhere, then the location matches /somewhere and it tries in two places sequentially to find a response, as specified by the try_files directive, responding with the first successful try.

  1. first it tests if there is a file at the location /somewhere, and if the file exists, it is returned in the response.
  2. if this fails it tries the try_files fallback option, @default, which is called a named_location. The response for this named_location is specified by the location @default directive. A named_location will never match an incoming request, and is used by reference to specify the response in other location directives.

In this way, an if statement can be avoided (if the file exists, then use it, else respond as spec'd in the location @default directive). So it can be used as a shorthand for an if condition. "If" statements are definitely "frowned upon" by the nginx authors (if is evil) as they have some limitations and may not give the expected result.

1
  • In which cases @default must be used instead of a location, containing internal directive?
    – AleXoundOS
    Jul 4, 2022 at 7:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .