Skip to content

Instantly share code, notes, and snippets.

@maullerz
Forked from hlubek/nginx.conf
Created April 3, 2024 03:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maullerz/8ff2693726fa6c52d3def5c7d182f8d2 to your computer and use it in GitHub Desktop.
Save maullerz/8ff2693726fa6c52d3def5c7d182f8d2 to your computer and use it in GitHub Desktop.
Nginx reverse proxy with caching for Next.js with imgproxy
# Based on https://steveholgado.com/nginx-for-nextjs/
# - /var/cache/nginx sets a directory to store the cached assets
# - levels=1:2 sets up a two‑level directory hierarchy as file access speed can be reduced when too many files are in a single directory
# - keys_zone=STATIC:10m defines a shared memory zone for cache keys named “STATIC” and with a size limit of 10MB (which should be more than enough unless you have thousands of files)
# - inactive=7d is the time that items will remain cached without being accessed (7 days), after which they will be removed
# - use_temp_path=off tells NGINX to write files directly to the cache directory and avoid unnecessary copying of data to a temporary storage area first
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=STATIC:10m inactive=7d use_temp_path=off;
upstream nextjs_upstream {
server localhost:3000;
}
upstream imgproxy_upstream {
server localhost:8080;
}
server {
listen 80 default_server;
server_name _;
server_tokens off;
gzip on;
gzip_proxied any;
gzip_comp_level 4;
gzip_types text/css application/javascript image/svg+xml;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
# Imgproxy paths can contain multiple slashes (e.g. local:///image/file.jpg)
merge_slashes off;
location /img/ {
proxy_cache STATIC;
proxy_pass http://imgproxy_upstream/;
# For testing cache - remove before deploying to production
add_header X-Cache-Status $upstream_cache_status;
}
location /_next/static {
proxy_cache STATIC;
proxy_pass http://nextjs_upstream;
# For testing cache - remove before deploying to production
add_header X-Cache-Status $upstream_cache_status;
}
location /static {
proxy_cache STATIC;
# Ignore cache control for Next.js assets from /static, re-validate after 60m
proxy_ignore_headers Cache-Control;
proxy_cache_valid 60m;
proxy_pass http://nextjs_upstream;
# For testing cache - remove before deploying to production
add_header X-Cache-Status $upstream_cache_status;
}
location / {
proxy_pass http://nextjs_upstream;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment