NGINX - Caching

1.Mount tmpfs (di Linux):

sudo mkdir -p /mnt/nginx_cache
sudo mount -t tmpfs -o size=512M tmpfs /mnt/nginx_cache

2.Tambahkan ke /etc/fstab supaya auto saat boot:

tmpfs /mnt/nginx_cache tmpfs defaults,size=512M 0 0

3.NGINX config:

http {
    include       mime.types;
    default_type  application/octet-stream;

    # Logging (optional)
    access_log  /var/log/nginx/access.log;
    error_log   /var/log/nginx/error.log;

    # Define zone untuk metadata cache
    proxy_cache_path /mnt/nginx_cache levels=1:2 keys_zone=cache_zone:50m
                     inactive=10m max_size=400m use_temp_path=off;

    upstream backend_app {
        # Bisa ganti ke IP backend atau port local
        server 127.0.0.1:3000;  # contoh: Node.js
        #server 127.0.0.1:9000; # contoh: PHP-FPM
    }

    server {
        listen 80;
        server_name _;

        location / {
            proxy_pass http://backend_app;

            # Set header biar backend tau client info
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

            # Cache logic
            proxy_cache cache_zone;
            proxy_cache_valid 200 302 10m;
            proxy_cache_valid 404 1m;

            # Optional: prevent cache untuk login/session dsb
            proxy_cache_bypass $http_authorization;
            proxy_no_cache $http_authorization;

            # Tambah info status cache
            add_header X-Cache-Status $upstream_cache_status;
        }
    }
}

4.Restart Nginx

systemctl restart nginx
Next Post
No Comment
Add Comment
comment url