不确定我是否想要完成不可能的事情,但我想配置Nginx将“.webp”文件提供给支持文件格式的浏览器并提供后备文件(即png,jpgs等)。 )到尚不支持WebP格式的浏览器。我也希望Nginx在检查视网膜支持并提供这些照片的原始版本或@ 2x尺寸版本时执行此操作。
/assets/img/
目录中名为'sample-photo'的图像的示例流程:
try_files
声明中可能会发生一些问题。非常感谢!
此代码位于我的文档的HTML头部。检查高分辨率支持并设置cookie:
<!-- Set the 'device-pixel-ratio' cookie with Javascript if hi-res is supported -->
<script type="text/javascript">
if (!document.cookie.match(/\bdevice-pixel-ratio=/)) {
document.cookie = 'device-pixel-ratio='
+ (window.devicePixelRatio > 1 ? '2' : '1') + '; path=/';
}
</script>
<!-- A CSS-only fallback of setting the 'device-pixel-ratio' cookie just in case browsers have Javascript disabled -->
<style type="text/css">
@media only screen and (-webkit-min-device-pixel-ratio : 2),
only screen and (min-device-pixel-ratio : 2) {
head {
background-image: url(/set-device-pixel-ratio/2);
}
}
</style>
这是我的大部分'nginx.conf'文件。为简洁起见,遗漏了一些部分:
user www-data;
http {
##
# Basic Settings
##
sendfile on;
include /etc/nginx/mime.types;
default_type application_octet-stream;
##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript
##
# Conditional variables--
# Define a variable called "$webp_suffix" if the HTTP Accept header contains the "webp" substring
# and populate it with 'webp', otherwise leave empty.
##
map $http_accept $webp_suffix {
default ""
"~*webp" ".webp";
}
}
最后,这是我为我的网站创建的服务器块:
server {
listen 80;
server_name localhost;
root /var/www;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
# Sets the device-pixel-ratio cookie
location ~ /set-device-pixel-ratio/(/d+)/? {
add_header Set-Cookie "device-pixel-ratio=$1;Path=/;Max-Age=31536000";
return 204; # nginx does not allow empty 200 responses
}
# Serve appropriate image assets
location ~(/assets/img/[^\.]+)(\.(?:jpg|jpeg|png|gif))$ {
# Naming convention for hi-res images:
set $hidpi_uri $1@2x$2;
if ($http_cookie !~ 'device-pixel-ratio=2') {
break;
}
try_files $hidpi_uri$webp_suffix $uri$webp_suffix $uri =404;
}
}