Nginx only caches file endpoints

15 Views Asked by At

I have two endpoints, one for downloading files and the other for normal JSON responses. Now, I want to automatically cache the responses of the endpoint that returns files in Nginx. Upon inspecting the responses in Postman, I noticed that the file endpoint returns a content-disposition header. Hence, I intend to use this header in the Nginx configuration to determine whether to cache the response. Below is my configuration:

server {
    listen 8081;


    proxy_cache wado_cache;
    proxy_cache_valid 200 60m;
    proxy_ignore_headers "Cache-Control" "Expires";


    location / {
        add_header hd_content_disposition "$upstream_http_content_disposition";
        proxy_pass http://192.168.1.2:8080/;
        proxy_cache_bypass $upstream_http_content_disposition; # 如果需要缓存,则绕过缓存
        proxy_hide_header Cache-Control; 
        add_header Nginx-Cache-Status "$upstream_cache_status";
    }
}

However, when I actually make requests, I find that both requests are being cached, and subsequently, the cached responses are being served. Below is my endpoint code:

from flask import Flask, send_file

app = Flask(__name__)

@app.route("/json")
def json():
    return {"hello": "world"}

@app.route("/json1")
def txt():
    file_path = "test.txt"
    return send_file(file_path, as_attachment=True)

if "__main__" == __name__:
    app.run(port=8080, host='0.0.0.0')

How can I configure to only cache endpoints that return files?

0

There are 0 best solutions below