![Nginx映像檔名透過使用正規表示式修改uri來刪除尺寸](https://rvso.com/image/697381/Nginx%E6%98%A0%E5%83%8F%E6%AA%94%E5%90%8D%E9%80%8F%E9%81%8E%E4%BD%BF%E7%94%A8%E6%AD%A3%E8%A6%8F%E8%A1%A8%E7%A4%BA%E5%BC%8F%E4%BF%AE%E6%94%B9uri%E4%BE%86%E5%88%AA%E9%99%A4%E5%B0%BA%E5%AF%B8.png)
在 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 ;
}