NGINX as a Reverse Proxy
[ 82 ]
Here, we're trying to determine which upstream to pass the request to, based on the
value of the $request_uri variable. This seems like a very reasonable configuration
at first glance, because it works for our simple test cases. But the images will neither
be served from the /img filesystem location, the /static filesystem location, nor
from the @imageserver named location. try_files simply doesn't work when an
if directive is present in the same location. if creates an implicit location with its
own content handler; in this case, the proxy module. So the outer content handler,
where try_files is registered, won't ever get invoked. There is a way to write this
configuration differently to make it do what we want.
Let's think about our request as NGINX processes it. After having found a matching
IP and port, it first selects a virtual host (server) based on the Host header. Then, it
scans all locations under this server, looking for a matching URI. So, we see that the
better way to configure a selector based on the URI is in fact by defining multiple
locations, as shown in the following example:
location /blog {
proxy_pass http://127.0.0.1:9000;
}
location /tickets {
proxy_pass http://tickets.example.com;
}
location /img {
try_files /static @imageserver;
}
location / {
root /static;
}
location @imageserver {