Using mod_negotiation to serve webp if UA requests it

Can mod_negotiation be used to serve a web image if the browser supports it, and jpg otherwise?

For example, if I refer to an image using the path / images / test, does it serve for the image found on /images/test.webp if UA knows about webp or jpg otherwise?

I tried to talk, but it seems that the Accept headers in Chrome at least look like Accept:*/* , and not set the image type.

If this is not a way to do this, does anyone have any other suggestions?

+7
source share
2 answers

To serve WebP images, I use the rewrite rule in nginx, which checks for file availability and WebP image support. I put it in Apache mod_rewrite since the OP mentioned mod_negotiation. The rewrite looks for a user agent containing the word "chrome" and checks the file with the extension .webp with the same name and path as the .jpg or .png file, and if so, then the WebP file is used. The rewrite rule is a bit cloned, but it does its job.

 AddType image/webp .webp # strip the extension off of all JPGs RewriteCond %{HTTP_USER_AGENT} (chrome) [NC] RewriteRule (.*)\.jpg$ $1 #check for a webp file, if so serve it RewriteCond %{REQUEST_FILENAME}.webp -f RewriteRule (.*) $1.webp [E=WEBP:1] #check for if we did not have a webp file and we do have a jpg, if so serve it RewriteCond %{REQUEST_FILENAME}.jpg -f RewriteCond %{REQUEST_FILENAME}.webp !-f RewriteRule (.*) $1.jpg # strip the extension off of all PNGs RewriteCond %{HTTP_USER_AGENT} (chrome) [NC] RewriteRule (.*)\.png$ $1 #check for a webp file, if so serve it RewriteCond %{REQUEST_FILENAME}.webp -f RewriteRule (.*) $1.webp [E=WEBP:1] #check for if we did not have a webp file and we do have a png, if so serve it RewriteCond %{REQUEST_FILENAME}.png -f RewriteCond %{REQUEST_FILENAME}.webp !-f RewriteRule (.*) $1.png 

For my site, I have the option to upload my photos via JavaScript after I can detect WebP support in the browser instead of relying on a user agent string. If there is WebP support, than I set a cookie before starting to download the images. Therefore instead RewriteCond

 RewriteCond %{HTTP_USER_AGENT} (chrome) [NC] 

I would use this

 RewriteCond %{HTTP_COOKIE} supports_webp 
+2
source

An Accept header is not required, and when provided with meaningful values, it simply tells the server what types of content the client should receive for this particular request.

In the past, for example, when png was not supported well, I used such rules (adapted to your question). Webp is supported by two browsers, which makes the rules pretty simple.

 RewriteEngine On RewriteCond %{HTTP_USER_AGENT} \ Chrome/ [OR] RewriteCond %{HTTP_USER_AGENT} Opera.*Version/11.1 RewriteRule .* - [E=imgext:webp,T=image/webp] RewriteCond %{ENV:imgext} !webp RewriteRule .* - [E=imgext:jpg] RewriteCond %{REQUEST_URI} ^/images/ RewriteCond %{REQUEST_FILENAME} !-s RewriteRule (.*) $1\.%{ENV:imgext} [QSA] 
+1
source

All Articles