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;
server_name siriad.com;
rewrite ^/(.*) http://www.siriad.com/$1 permanent;
}
server {
listen [::]:80;
server_name www.siriad.com
testing.siriad.com;
access_log /var/log/nginx/siriad.com/access.log;
error_log /var/log/nginx/siriad.com/error.log;
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 www.siriad.com and subsequently load testing.siriad.com, I would end up with the cached content from www.siriad.com 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 siriad.com as well as testing.siriad.com. I am hoping this post is slightly more searchable than the results I was getting while trying to find the answer to this problem.