Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vukhanhtruong/7ecc9c515e051e963c222eb919b8b7f9 to your computer and use it in GitHub Desktop.
Save vukhanhtruong/7ecc9c515e051e963c222eb919b8b7f9 to your computer and use it in GitHub Desktop.
NGINX as caching REST-API Proxy
upstream backend {
server localhost:8080;
#server backup1.example.com:8080 backup;
#server backup2.example.com:8080 backup;
}
# Set cache dir
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=one:10m;
# Set cache key to include identifying components
proxy_cache_key $scheme$proxy_host$request_uri;
# Add cache status to log
log_format cache '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" cs=$upstream_cache_status';
server {
listen 80;
server_name localhost;
## Access and error logs.
access_log /var/log/nginx/api-proxy.access.log cache;
error_log /var/log/nginx/api-cache.error.log;
## Server certificate and key.
#ssl_certificate ssl/example.com.crt;
#ssl_certificate_key ssl/example.com.key;
add_header X-Cache-Status $upstream_cache_status;
location / {
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://backend;
proxy_cache one;
proxy_ignore_headers X-Accel-Expires Expires Cache-Control;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment