0

Considering a nginx server with the following two locations which each serve a webapp, including some static resources and a REST API. Is there a way to cache the common resources, e.g. /proxy/host1/js/vendors.js and /proxy/host2/js/vendors.js such that nginx only downloads vendors.js once from an upstream webapp server and caches it for requests of vendors.js to different hosts.

location /proxy/host1 {
  rewrite /proxy/host1/(.*) /$1  break;
  proxy_pass http://host1;

  proxy_set_header X-Forwarded-Proto $scheme;
  proxy_set_header HOST $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
  proxy_read_timeout     300;
  proxy_connect_timeout  300;
}

location /proxy/host2 {
  rewrite /proxy/host2/(.*) /$1  break;
  proxy_pass http://host2;

  proxy_set_header X-Forwarded-Proto $scheme;
  proxy_set_header HOST $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
  proxy_read_timeout     300;
  proxy_connect_timeout  300;
}
Coxer
  • 187
  • 1
  • 14

1 Answers1

0

You can modify the cache key used by nginx with proxy_cache_key directive.

A warning: You need to understand the caching system in detailed level before adjusting the key, because incorrect settings might lead to issues that are hard to debug.

For example, two separate URLs that are supposed to show different content always show content from one of the URLs.

The default is `proxy_cache_key $scheme$proxy_host$request_uri";

You could create a custom URI for the key by using a map:

map $request_uri $cache_uri {
    default $request_uri;
    ~ /js/vendors.js\?? /shared/vendors.js;
}

server {
    proxy_cache_key "$scheme$proxy_host$cache_uri";

    ...
}

The map above assigns cache key /shared/vendors.js for all URIs that contain /js/vendors.js? string.

This means that for all such URLs, a single copy is stored in cache.

Tero Kilkanen
  • 36,796
  • 3
  • 41
  • 63