用nginx有条件地提供高分辨率和WebP图像

不知道如果我试图拉下不可能的,但我想要configurationNginx服务“.webp”文件到浏览器支持文件格式和服务回退文件(即PNG,JPG等)到浏览器那还不支持WebP格式。 我也希望Nginx能够在检查视网膜支持和服务这些照片的原始或@ 2x大小的版本时做到这一切。

/assets/img/目录中称为“sample-photo”的图片的示例stream程:

  • 检查浏览器是否支持WebP,如果是高分辨率设备,请input:“assets / img / [email protected]
  • 设备可能不是高分辨率,因此可以提供:“assets / img / sample-photo.webp”
  • 也许WebP不被支持,但设备是高分辨率,所以服务:“assets / img / [email protected]
  • 浏览器不支持WebP和设备不是高分辨率,服务:“assets / img / sample-photo.png”

我自己刺了一下,但没有太多的运气。 我发现了两个令人敬畏的post,帮助我开始了正确的方向。 下面是我的代码。 真的很感激任何见解和帮助。 我的第一个想法是,也许在最后的try_files声明中有一些不可思议的事情发生。 非常感谢!

  1. 有条件地提供高分辨率的图像
  2. nginx有条件地处理文件

此代码位于我的文档的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"; } } 

最后,这是我为我的网站创build的服务器块:

 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; } } 

在你的try_files指令中,查找映像$uri$webp_suffix ,该映像parsing为image.png.webp 。 我想你想在那里寻找$1$webp_suffix

否则,我build议您在主configuration中启用nginx debug_connection <your_IP>指令,并且您将获得请求过程中发生的详细日志。 在那里你可以更好地看到发生了什么。 如果你不能解决这个问题,请将请求的日志添加到问题中,我们可以帮助更好。