簡體   English   中英

在 nginx 反向代理的所有文件夾級別緩存圖像

[英]Caching images on all folder levels of nginx reverse proxy

我正在嘗試為我的開源圖像托管服務PictShare緩存圖像。

Pictshare 有一個智能查詢系統,其中上傳的圖像可以位於更改圖像的“虛擬子目錄”中。 例如,這是上傳的 stackoverflow 徽標的鏈接: https : //www.pictshare.net/6cb55fe938.png

我可以通過將/300/添加到圖像名稱之前的 URL 將其調整為 300 寬度: https : //www.pictshare.net/300/6cb55fe938.png

由於我最近處理大量流量,我希望我的 nginx 代理能夠緩存所有虛擬子文件夾中的所有圖像,但它不起作用。 我已經閱讀了許多文章和許多 stackoverflow 帖子,但沒有任何解決方案對我有用。

到目前為止,這是我高效的 vhost 文件

proxy_cache_path /etc/nginx/cache/pictshare levels=1:2 keys_zone=pictshare:50m max_size=1000m inactive=30d;
proxy_temp_path /etc/nginx/tmp 1 2;
proxy_cache_key "$scheme$request_method$host$request_uri";

proxy_ignore_headers "Set-Cookie";
proxy_hide_header "Set-Cookie";
proxy_buffering on;

server {
...
location / {
        proxy_pass          http://otherserver/pictshare/;
        include /etc/nginx/proxy_params;

        location ~* \.(?:jpg|jpeg|gif|png|ico)$ {
          expires max;
          proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
          proxy_cache_valid 200 301 302 1y;
          proxy_cache pictshare;
          proxy_pass          http://otherserver/pictshare$request_uri;
        }

    }
}

問題是沒有緩存任何文件,我看到代理目標上的每個圖像請求。

我讓它工作的唯一方法是向顯式啟用緩存的主機文件添加一個特殊位置:

   location /cached {
       proxy_cache_valid 200 1y;
        proxy_cache pictshare;
        expires 1y;

        proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;

        include /etc/nginx/proxy_params;

        proxy_pass          http://otherserver/pictshare/thumbs/;
       proxy_cache_use_stale  error timeout invalid_header updating http_500 http_502 http_503 http_504;

        }

此解決方案的明顯問題是,僅當請求以/cached開頭時才會緩存圖像,例如: https : //www.pictshare.net/cached/6cb55fe938.png

將緩存命令添加到根目錄對我來說不是一個選擇,因為我不希望緩存表單和頁面,只緩存圖像

我的錯誤在哪里?

proxy_cache_path /etc/nginx/cache/pictshare levels=1:2 keys_zone=my_cache:50m max_size=3g inactive=180m;
proxy_temp_path /etc/nginx/tmp 1 2;
proxy_cache_key "$scheme$request_method$host$request_uri";

location ~* ^.+\.(jpe?g|gif|png|ico|pdf)$ {
    access_log off;
    include /etc/nginx/proxy.conf;
    proxy_pass http://backend;
    proxy_cache pictshare;
    proxy_cache_valid any 12h;
    add_header X-Proxy-Cache $upstream_cache_status;
    root /var/www/public_html/cached; }

location / {
    include /etc/nginx/proxy.conf;
    proxy_pass http://backend;
    root /var/www/public_html;
}

無論列出的順序如何,nginx 首先搜索由文字字符串給出的最具體的前綴位置。 在上面的配置中,唯一的前綴位置是“/”,並且由於它匹配任何請求,因此將用作最后的手段。 然后 nginx 按照配置文件中列出的順序檢查正則表達式給出的位置。 第一個匹配的表達式停止搜索,nginx 將使用這個位置。 如果沒有正則表達式匹配請求,則 nginx 使用之前找到的最具體的前綴位置。 http://nginx.org/en/docs/http/request_processing.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM