3

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?

  • I got it working by removing the "/$2/$1/$6" part after "@backend" in the try_files directive. But I still need these arguments. – ZogStriP Jan 23 '12 at 17:03
2

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;
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.