Skip to content

Instantly share code, notes, and snippets.

@dctrwatson
Last active December 5, 2023 05:07
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save dctrwatson/5785675 to your computer and use it in GitHub Desktop.
Save dctrwatson/5785675 to your computer and use it in GitHub Desktop.
Caching NPM proxy using Nginx
user www-data;
worker_processes 4;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
access_log off;
default_type application/octet-stream;
sendfile on;
tcp_nodelay on;
tcp_nopush off;
reset_timedout_connection on;
server_tokens off;
# Cache 10G worth of packages for up to 1 month
proxy_cache_path /var/lib/nginx/npm levels=1:2 keys_zone=npm:16m inactive=1M max_size=10G;
# Multiple server definitions makes nginx retry
upstream registry_npm {
server registry.npmjs.org;
server registry.npmjs.org;
keepalive 16;
}
gzip on;
gzip_types application/json text/css text/javascript;
gzip_proxied any;
gzip_vary on;
server {
listen 80 default_server;
server_name npm.example.com;
root /var/www;
proxy_cache npm;
proxy_cache_key $uri;
proxy_cache_lock on;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_http_version 1.1;
proxy_pass_request_headers off;
proxy_set_header Host registry.npmjs.org;
location / {
proxy_cache_valid any 5m;
add_header X-Cache $upstream_cache_status;
proxy_pass http://registry_npm;
}
location ~ ^/.+/-/.+ {
proxy_cache_valid any 1M;
add_header X-Cache $upstream_cache_status;
proxy_pass http://registry_npm;
}
}
}
@chrissnell
Copy link

@Puneeth-n did you ever figure out a solution for this issue?

@clonejo
Copy link

clonejo commented Aug 7, 2020

I needed to add proxy_ignore_headers Set-Cookie; as well. https://www.nginx.com/blog/nginx-caching-guide/#Frequently-Asked-Questions-(FAQ)

@JaosnHsieh
Copy link

it works, thank you!

@dovidweisz
Copy link

dovidweisz commented Dec 5, 2023

Would you extend caching to like a month? Turning this into a full mirror?

Some endpoints would need shorter caching periods. I wonder if npm itself sends caching headers that can be used.

Another idea would be to extend caching only for the .tgz files.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment