|
| 1 | +user nobody; |
| 2 | +worker_processes 1; |
| 3 | +daemon off; |
| 4 | + |
| 5 | +env npm_config_registry; |
| 6 | + |
| 7 | +events { |
| 8 | + worker_connections 1024; |
| 9 | +} |
| 10 | + |
| 11 | + |
| 12 | +http { |
| 13 | + # We literally only care about 2 types of files/payloads. |
| 14 | + types { |
| 15 | + application/json json; |
| 16 | + application/gzip tgz; |
| 17 | + } |
| 18 | + default_type application/octet-stream; |
| 19 | + sendfile on; |
| 20 | + keepalive_timeout 65; |
| 21 | + proxy_cache_path /tmp/npm-cache levels=1:2 keys_zone=STATIC:10m inactive=24h max_size=1g; |
| 22 | + server { |
| 23 | + listen 4873; |
| 24 | + set $npm_config_registry ''; |
| 25 | + set $upstream_base ''; |
| 26 | + set_by_lua_block $upstream_base { |
| 27 | + local upstream = os.getenv("npm_config_registry") |
| 28 | + -- escape . and - which have special meaning in Lua patterns |
| 29 | + upstream = upstream:gsub("%.", "%%."):gsub("%-", "%%-"):gsub("/+$", "") |
| 30 | + ngx.log(ngx.ERR, 'using upstream base:', upstream) |
| 31 | + return upstream |
| 32 | + } |
| 33 | + set_by_lua_block $npm_config_registry { |
| 34 | + local upstream = os.getenv("npm_config_registry"):gsub("/+$", "") |
| 35 | + ngx.log(ngx.ERR, 'using upstream server:', upstream) |
| 36 | + return upstream |
| 37 | + } |
| 38 | + location ~ ^/.*\.tgz$ { |
| 39 | + resolver 127.0.0.1 ipv6=off; |
| 40 | + proxy_pass $npm_config_registry; |
| 41 | + proxy_cache STATIC; |
| 42 | + proxy_cache_valid 200 1d; |
| 43 | + proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504; |
| 44 | + } |
| 45 | + location / { |
| 46 | + resolver 127.0.0.1 ipv6=off; |
| 47 | + proxy_pass $npm_config_registry; |
| 48 | + proxy_buffers 32 1m; |
| 49 | + proxy_cache STATIC; |
| 50 | + proxy_cache_valid 200 1d; |
| 51 | + proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504; |
| 52 | + # need to disable encoding in order to be able to filter the response body |
| 53 | + proxy_set_header Accept-Encoding ""; |
| 54 | + # modifying the response body will change the length |
| 55 | + header_filter_by_lua_block { |
| 56 | + ngx.header.content_length = nil |
| 57 | + } |
| 58 | + # replace all occurances of, eg. https://registry.npmjs.org with http://127.0.0.1:4873 |
| 59 | + body_filter_by_lua_block { |
| 60 | + local upstream = ngx.var.upstream_base |
| 61 | + -- need to construct URL because we may be proxying http<->https |
| 62 | + local base = ngx.var.scheme .. '://' .. ngx.var.http_host |
| 63 | + ngx.log(ngx.ERR, "Modifying JSON of " .. ngx.var.uri .. " to replace '" .. upstream .. "' with '" .. base .. "'") |
| 64 | + ngx.arg[1] = string.gsub(ngx.arg[1], upstream, base) |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments