Mar 162011

This post discusses the nginx proxy module. I recently setup Nginx as a reverse caching proxy for various sites. Every configuration example I came across online failed to mention using the proxy_cache_key directive. Therefore, I originally ended up with something like this:

# cat /etc/nginx/sites-available/siriad
# You may add here your
# server {
#       ...
# }
# statements for each of your virtual hosts to this file

server {
        listen   [::]:80;
        rewrite ^/(.*)$1 permanent;

server {
        listen   [::]:80;

        access_log      /var/log/nginx/;
        error_log       /var/log/nginx/;

        location / {
                proxy_pass              http://backend;
                proxy_set_header        Host $host;
                proxy_cache             siriad;
                proxy_cache_valid       200 1d;
                proxy_cache_use_stale   error timeout invalid_header updating
                                        http_500 http_502 http_503 http_504;

This led to some odd behavior. When I would load and subsequently load, I would end up with the cached content from for both requests. The cache was working, but was not distinguishing between the two hosts. I spent some time trying different configurations thinking that this was a problem caused by me since I had trouble finding any information on it.

It turns out, this is exactly the use case for the proxy_cache_key directive. By adding the following line, I made sure that the hostname was included in the key used to cache the request so that there were no key collisions during the process.

                proxy_cache_key         "$scheme$host$request_uri";

I was able to find this information after searching around DDG for quite a while. I finally came across this forum post. The result of the above configuration is a working reverse caching proxy using Nginx for as well as I am hoping this post is slightly more searchable than the results I was getting while trying to find the answer to this problem.

 Posted by at 18:53

  7 Responses to “Nginx caching with multiple vhosts”

  1. Dude – you saved me / us! We had the exact problem and I could not find this quick enough! Thank you!!

  2. This isn’t intuitive at all for someone which doesn’t know the inners of the nginx cache system, so thank you for saving the day 🙂

    • I agree. The nginx documentation is actually pretty good. The problem is mainly that most examples didn’t have the directive I needed.

  3. wow, thanks about this change on proxy_cache_path! I used a website with multiple domains and $proxy_port was messing the cache!!

  4. Saved the day. Thanks a lot sir!

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>