How can I have same rule for two locations in NGINX config?
Another option is to repeat the rules in two prefix locations using an included file. Since prefix locations are position independent in the configuration, using them can save some confusion as you add other regex locations later on. Avoiding regex locations when you can will help your configuration scale smoothly.
server {
location /first/location/ {
include shared.conf;
}
location /second/location/ {
include shared.conf;
}
}
Here's a sample shared.conf:
default_type text/plain;
return 200 "http_user_agent: $http_user_agent
remote_addr: $remote_addr
remote_port: $remote_port
scheme: $scheme
nginx_version: $nginx_version
";
Try
location ~ ^/(first/location|second/location)/ {
...
}
The ~
means to use a regular expression for the url. The ^
means to check from the first character. This will look for a /
followed by either of the locations and then another /
.
Both the regex and included files are good methods, and I frequently use those. But another alternative is to use a "named location", which is a useful approach in many situations — especially more complicated ones. The official "If is Evil" page shows essentially the following as a good way to do things:
error_page 418 = @common_location;
location /first/location/ {
return 418;
}
location /second/location/ {
return 418;
}
location @common_location {
# The common configuration...
}
There are advantages and disadvantages to these various approaches. One big advantage to a regex is that you can capture parts of the match and use them to modify the response. Of course, you can usually achieve similar results with the other approaches by either setting a variable in the original block or using map
. The downside of the regex approach is that it can get unwieldy if you want to match a variety of locations, plus the low precedence of a regex might just not fit with how you want to match locations — not to mention that there are apparently performance impacts from regexes in some cases.
The main advantage of including files (as far as I can tell) is that it is a little more flexible about exactly what you can include — it doesn't have to be a full location block, for example. But it's also just subjectively a bit clunkier than named locations.
Also note that there is a related solution that you may be able to use in similar situations: nested locations. The idea is that you would start with a very general location, apply some configuration common to several of the possible matches, and then have separate nested locations for the different types of paths that you want to match. For example, it might be useful to do something like this:
location /specialpages/ {
# some config
location /specialpages/static/ {
try_files $uri $uri/ =404;
}
location /specialpages/dynamic/ {
proxy_pass http://127.0.0.1;
}
}