Nginx映像檔名透過使用正規表示式修改uri來刪除尺寸

Nginx映像檔名透過使用正規表示式修改uri來刪除尺寸

在 nginx 配置中,當給定 WordPress 圖像命名/大小符號約定找不到所需的圖像大小時,返回原始圖像的最佳方法是什麼。

因此,假設如果未找到 /image-name-150x170.png,我希望返回 /image-name.png。 -150-170部分可以是其他一些數字。因此,我希望刪除檔案名稱中點之前的破折號 1-4 位元 x 1-4 位元。

我想將 uri 程式碼中的替換放在 @static_full 位置區塊內或重寫。想知道哪個性能比較好。

#some locations here and then 

location ~* ^.+\.(png|gif|jpg|jpeg){
       access_log off; 
       log_not_found off; 
       expires max; 
       error_page 404 = @static_full;  #if not found, seek #static_ful
}

location @static_full{
  #modify uri here to remove image dimensions like below
  #uri = remove dash 1-4 digits x 1-4 digits before dot
  #or rewrite to original name 
 }

location / {
  try_files $uri $uri/ /index.php?$args ;
}

更新,我想出了怎麼做。下面做了我想做的事。

location @static_full{
  #modify uri here to remove image dimensions like below
  #uri = remove dash three digits x three digits before dot
  rewrite "^(.*)(-[\d]{1,4}+x[\d]{1,4}+.)([\w]{3,4})" $1.$3 break;
 }

答案1

您可以考慮使用try_files而不是error_page指令。

try_files $uri @static_full;

這個文件了解詳情。

編輯 - 添加完整的解決方案:

location ~* ^.+\.(png|gif|jpg|jpeg) {
    try_files $uri @static_full;

    access_log off; 
    log_not_found off; 
    expires max; 
}

location @static_full {
    rewrite "^(.*)(-[\d]{1,4}+x[\d]{1,4}+.)([\w]{3,4})" $1.$3 break;
}

location / {
    try_files $uri $uri/ /index.php?$args ;
}

相關內容