Skip to content

Instantly share code, notes, and snippets.

@SunRed
Forked from fennb/gist:1283573
Last active November 30, 2020 11:09
Show Gist options
  • Save SunRed/882c2d291c0acda80b9cec94a8aac43e to your computer and use it in GitHub Desktop.
Save SunRed/882c2d291c0acda80b9cec94a8aac43e to your computer and use it in GitHub Desktop.
nginx microcaching config example for a Nextcloud instance behind a proxy (E.g. Nextcloud on Raspberry Pi tunnelled through WireGuard to a public server)
# Set cache dir
proxy_cache_path /var/cache/nginx levels=1:2
keys_zone=microcache:5m max_size=1000m;
# Virtualhost/server configuration
server {
listen 443;
listen [::]:443;
server_name yourhost.domain.com;
# Replace HSTS header
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
# Define cached location (may not be whole site)
location / {
# Setup var defaults
set $no_cache "";
# If non GET/HEAD, don't cache
if ($request_method !~ ^(GET|HEAD)$) {
set $no_cache "1";
}
# Bypass cache if no-cache cookie is set
if ($http_cookie ~* "nc_username|nc_token|nc_session_id") {
set $no_cache "1";
}
# Bypass cache on certain query string in request uri to prevent redirect loop
if ($query_string ~* "clear=1") {
set $no_cache "1";
}
# Bypass cache if flag is set
proxy_no_cache $no_cache;
proxy_cache_bypass $no_cache;
# Point nginx to the real app/web server
proxy_pass http://appserver.domain.com;
proxy_http_version 1.1;
proxy_socket_keepalive on;
# Remove HSTS header from nextcloud instance response
proxy_hide_header Strict-Transport-Security;
# Rewrite non-SSL redirects
proxy_redirect http:// https://;
# Set cache zone
proxy_cache microcache;
# Set cache key to include identifying components
proxy_cache_key $scheme$host$request_method$request_uri;
# Only cache valid HTTP responses
proxy_cache_valid 200 301 12h;
proxy_cache_valid 302 404 1h;
# Serve from cache if currently refreshing
proxy_cache_use_stale updating;
# Send appropriate headers through
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_set_header X-Forwarded-Proto $scheme;
# Set files larger than 1M to stream rather than cache
proxy_max_temp_file_size 1M;
# Custom logging
log_format custom '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" nocache:$no_cache';
access_log /var/log/nginx/microcache.log custom;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment