Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I am using nginx in reverse proxy mode. In my server section I have this code to set expire and cache control of my static files.

     location ~* ^.+\.(css|js|png|gif)$ {
         access_log off;
         expires max;
         add_header Cache-Control public;
         if (!-f $request_filename) {
           proxy_pass  http://localhost:82;
         }

     }

This is quite obviously creating issues. Can someone help me correct this code to use try_files or rewrite?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

There are at least 2 techniques.

error_page

Before the introduction of try_files directive the common method was to intercept error code 404 and process the request with a named location, e.g.

location ~* \.(css|js|png|gif)$ {
  access_log off;
  expires max;
  add_header Cache-Control public;
  error_page 404 = @upstream;
}

try_files

The equivalent using try_files would be

location ~* \.(css|js|png|gif)$ {
  access_log off;
  expires max;
  add_header Cache-Control public;
  try_files $uri @upstream;
}

And the named location is the same for both scenarios:

location @upstream {
  proxy_pass http://localhost:82;
}
share|improve this answer
    
thanks for the try files. error_page seems dirty –  Quintin Par Jun 22 '11 at 8:26
    
I completely agree, that using error_page seems like a hack, but in fact it is very powerful instrument. This particular use case is so frequent, that Nginx author decided to introduce try_files. –  Alexander Azarov Jun 22 '11 at 16:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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