0

Take this Nginx location config as example:

location ~* \.(gif|jpg|jpeg|swf|css)$ {
  add_header Cache-Control "max-age=259200, public";
}

location ^~ /abc/ {
  try_files $uri /abc/generic.png;
}

For request /abc/x.jpg, it will match the 2nd location, and the response will NOT have Cache-Control header. How do I do to have the Cache-Control header applied to /abc/x.jpg as well?

Something like this would work, but it is kinda duplicating.

location ~* \.(gif|jpg|jpeg|swf|css)$ {
  add_header Cache-Control "max-age=259200, public";
}

location ^~ /abc/ {
  try_files $uri /abc/generic.png;

  location ~* \.(gif|jpg|jpeg|swf|css)$ {
    add_header Cache-Control "max-age=259200, public";
  }
}
starchx
  • 433
  • 10
  • 23
  • That doesn't look like Nginx format to me. The way to work out if a block is triggered is to use the "add_header" directive, but you need to compile in the "headers more" module. Then use curl or Firefox with the extension "live http headers" to inspect. Tutorial here https://www.photographerstechsupport.com/tutorials/hosting-wordpress-on-aws-tutorial-part-2-setting-up-aws-for-wordpress-with-rds-nginx-hhvm-php-ssmtp/#nginx-source – Tim Jan 13 '17 at 04:46
  • Sorry, it was Puppet Hiera data. I have edited the question. Thanks. – starchx Jan 13 '17 at 06:17
  • My best guess is your problem is the leading slash, but I'd say my chances of being right here are 50/50 at best. You need a regular expression tool, like the one I use - https://regex101.com/ – Tim Jan 13 '17 at 06:31
  • 3
    https://nginx.org/r/include – Michael Hampton Jan 13 '17 at 06:58

1 Answers1

0

You could use something like this.

location ~* \.(gif|jpg|jpeg|swf|css)$ {
  add_header Cache-Control "max-age=259200, public";
}

location /abc {
  try_files $uri /abc/generic.png;
}

in Nginx the priority goes like this first = (equal) , then ^~ (no regular expression) , then ~ (case sensitive), then ~* (case insensitive) , then none. since the code was changed to /abc, its priority goes to the bottom, and therefore the first location block is called first when an URI which ends with the given image extension is found. and if it's not found, and if the URI contains /abc block something as /abc/file/file.pdf, /abc/file.pdf the other location block is called.

Don Dilanga
  • 232
  • 2
  • 8
  • Base my testing, /abc/file.png will only match to first block, regardless the file exists or not. If the file doesn't exist, Nginx simply return 404, ignoring the try_files. – starchx Jan 15 '17 at 23:55
  • If you had added png extension of course. not really, you don't understand what I am saying, I said if the condition in the first block isn't met, it will pick the next block if its condition is met. – Don Dilanga Jan 16 '17 at 15:31
  • 1
    Sorry, yes, I do have .png in the first block... Your answer is correct if png is not in the first block. – starchx Jan 16 '17 at 23:02