12

When you use the add_header directive in nginx, the header is added to the response coming from the origin server.

Say the origin server returns cache-control public, max-age=60. But in the nginx reverse proxy location you set something like:

add_header cache-control public, max-age=10

What does this do exactly? There are 2 different scenarios I can think of:

1) Nginx respects the cache-control header from the origin server and stores the content in its cache with an expiration of 60 secs. Then passes on the response with an overwritten header causing the client to store the resource in its cache with an expiration of 10s.

or..

2) Nginx overwrites the response headers first and then interprets them. It stores the resource with an expiration of 10 secs and passes the response to the client which also caches the it with an expiration of 10 secs.

3 Answers 3

13

Nginx adds its header just before the origin server, so you will have:

cache-control: public, max-age=10
cache-control: public, max-age=60

and the origin header will replace the nginx header.

The solution? Use nginx v1.4.3 that has the module more_set_headers and more_clear_headers in order to replace or clear the headers from origin.

You can download the module from here.
Here how to download nginx 1.4.3 and how to install it.
Here how to use the directives.

Sign up to request clarification or add additional context in comments.

1 Comment

The same thing can be achieved with the directive expires 10;, without using any third-party module.
6

If you want to totally discard the original servers header you can add:

proxy_hide_header 'Cache-Control';
add_header 'Cache-Control' "public, max-age=10";

This will strip the original header and add your own.

2 Comments

If you just want to hard-code your Cache-Control header in NGINX and don't care about the upstream server's response headers - this seems to be the easiest solution.
Note that unlike add_header, proxy_hide_header isn’t available inside if blocks.
0

Jon Betts’s answer is useful when you only want a Cache-Control header.

If you don’t mind also adding an Expires header, the following one-liner replaces the upstream header with a new Cache-Control header and an equivalent Expires header

expires 10;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.