Proxy to "backend" service whenever a file does not exists
5,445
If you use named captures for the captures, you can use them to rewrite the request in your named location:
server {
listen 80;
server_name .example.com;
root /var/www;
## Serves file (matching pattern: /<size>/<MEDIA>/<file na-me><.ext>)
location / {
## ?<name> assigns the capture to variable $name
location ~* ^/(?<size>\d+x\d+)/(?<guid>([\w])([\w])([\w])[-\w]+)/[^\.]+\.(?<ext>\w+)$ {
try_files /$3/$4/$5/$2/$1.$6 @backend;
}
}
## backend service
location @backend {
## rewrite ... break; just sets $uri and doesn't perform a redirect.
rewrite ^ /$guid/$size/$ext break;
proxy_pass http://127.0.0.1:8080;
}
}
Related videos on Youtube
Author by
ZogStriP
Updated on September 18, 2022Comments
-
ZogStriP over 1 year
I'm using NGINX to serve static file.
Whenever a file does not exist, I want NGINX to hit a nodejs backend service that will try to asynchronously retrieve that file.
The backend service needs 3 arguments: the GUID, the size and the extension of the file. All these arguments are retrieved from the original request using a regex.
Here is my current NGINX configuration file:
server { listen 80; server_name .example.com; root /var/www; ## Serves file (matching pattern: /<size>/<MEDIA>/<file na-me><.ext>) location / { location ~* ^/(\d+x\d+)/(([\w])([\w])([\w])[-\w]+)/[^\.]+\.(\w+)$ { try_files /$3/$4/$5/$2/$1.$6 @backend/$2/$1/$6; } } ## backend service location @backend { proxy_pass http://127.0.0.1:8080; } }
But I keep getting this error:
2012/01/23 11:53:31 [error] 28354#0: *1 could not find named location "@backend/ed3269d1-f9ef-4Ffc-dbea-5982969846c0/200x240/jpg", client: XXX.XXX.XXX.XXX, server: example.com, request: "GET /200x240/ed3269d1-f9ef-4Ffc-dbea-5982969846c0/my%20fil.jpg HTTP/1.1", host: "3.example.com"
Any idea how I can get NGINX to "proxy" the request to the backend service instead of looking for a file?
-
ZogStriP over 12 yearsI got it working by removing the "/$2/$1/$6" part after "@backend" in the try_files directive. But I still need these arguments.
-