Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have multiple location blocks use the same named @location

Tags:

php

nginx

I am trying to create a nginx conf file that has little repetition in it. I am using nginx to serve static files, and it proxies 404s or php content to the named location @varnish:

location @varnish {
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass_header Set-Cookie;
    proxy_pass http://localhost:6081;
    proxy_set_header Request-URI $request_uri;
}

For the "standard" situation whereby nginx should check to see if it has a file and then pass through to the backend, the following works fine:

location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    access_log        off;
    add_header      Pragma public;
    add_header Cache-Control "public, must-revalidate, proxy-revalidate";
    expires           max;
    open_file_cache_valid 120m;
    try_files $uri @varnish;
}

However, for PHP, I don't even want it to try the file, it should just immediately redirect the request to @varnish:

location ~ \.php$ {
    rewrite . @varnish last;
}

However, this does not appear to work. It seems a pain to have two separate near identical blocks (one for @backend and one for php) both referencing the same proxy, and is the sort of issue where humans can forget to put something in one and not the other.

like image 641
shrikeh Avatar asked Jun 14 '12 10:06

shrikeh


1 Answers

If you put the proxy settings into the server context and let the locations inherit them, then it's not much to duplicate. You can also set up an upstream block to make it easier to change the proxy target should you need to:

upstream _varnish {
  server localhost:6081;
}

server {
  proxy_redirect off;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header Request-URI $request_uri;
  proxy_pass_header Set-Cookie;

  location @varnish {
    proxy_pass http://_varnish;
  }

  location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    access_log off;
    add_header Pragma public;
    add_header Cache-Control "public, must-revalidate, proxy-revalidate";
    expires max;
    open_file_cache_valid 120m;
    try_files $uri @varnish;
  }

  location ~ \.php$ {
    proxy_pass http://_varnish;
  }
}
like image 191
kolbyjack Avatar answered Nov 02 '22 00:11

kolbyjack