使用nginx作為web快取的正確方法

使用nginx作為web快取的正確方法

我正在嘗試使用 nginx 作為網路快取(但沒有成功)。

我的系統是 Ubuntu 16.04 伺服器,其中 nginx 是 Gunicorn Web 伺服器(它是 Django 應用程式)的反向代理。

為了配置 Web 緩存,我在文件頂部添加了以下幾行virtual host( 中的那一行sites-available):

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=static_cache:10m max_size=90m;
proxy_cache_key "$scheme$request_method$host$request_uri$is_args$args";
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;

接下來,在主server範圍內,我有以下程式碼片段(我在其中註入了快取指令):

location @https_proxy_to_app {
    proxy_cache static_cache;
    proxy_cache_bypass $http_cache_control;
    add_header X-Proxy-Cache $upstream_cache_status;

    proxy_set_header X-Forwarded-Proto https;
    # additional proxy parameters
    include proxy_params;

    proxy_redirect off;
    proxy_pass http://app_server;
}

當我嘗試捲曲靜態資產 uri 時,這不會產生快取命中或未命中(這是測試快取是否正常運作的唯一方法)。因此,緩存無法運行。這就是我的意思:

嘗試curl -X GET -I https://example.com/static/css/my_app.css產量:

HTTP/1.1 200 OK
Server: nginx
Date: Wed, 22 Jan 2020 08:05:37 GMT
Content-Type: text/css
Content-Length: 26597
Last-Modified: Fri, 03 Jan 2020 14:23:59 GMT
Connection: keep-alive
Vary: Accept-Encoding
ETag: "5e0f4e7f-67e5"
Expires: Thu, 31 Dec 2037 23:55:55 GMT
Cache-Control: max-age=315360000
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Accept-Ranges: bytes

這是有問題的,因為它應該包含X-Proxy-Cache: HITor X-Proxy-Cache: MISS。請幫我診斷問題。


以下是我的所有location區塊(按出現順序):

location ~* \.(?:ico|css|js|gif|jpg|jpeg|png|svg|woff|ttf|eot)$ {

    root /home/ubuntu/app/myproj/;
    access_log off;
    error_log off;

}

# shows number of connections at https://example.com/status_nginx
location /status_nginx {
    stub_status on;
    allow 127.0.0.1;
    deny all;
}

location / {

    limit_conn conn_limit_per_ip 20;
    limit_req zone=req_limit_per_ip burst=10 nodelay;

    limit_req_log_level warn;

    #proxy_pass_request_headers on;
    proxy_buffering on;
    proxy_buffers 24 4k;
    proxy_buffer_size 2k;
    proxy_busy_buffers_size 8k;

    try_files $uri @https_proxy_to_app;
}

location @https_proxy_to_app {

    proxy_cache static_cache;
    proxy_cache_bypass $http_cache_control;
    add_header X-Proxy-Cache $upstream_cache_status;

    proxy_set_header X-Forwarded-Proto https;
    # additional proxy parameters
    include proxy_params;

    proxy_redirect off;
    proxy_pass http://app_server;
}

答案1

您的.css檔案是使用配置中的以下區塊提供的:

location ~* \.(?:ico|css|js|gif|jpg|jpeg|png|svg|woff|ttf|eot)$
    root /home/ubuntu/app/myproj/;
    access_log off;
    error_log off;
}

這意味著 nginx 直接發送文件,而不使用上游伺服器來處理請求。這意味著沒有執行緩存。

如果您.css從清單中刪除擴展名,並且您root沒有指向可以找到此 CSS 檔案的目錄,則請求將通過proxy_pass上游伺服器。

然後,只要上游伺服器設定了適當的 HTTP 快取標頭,回應就會被快取。

相關內容