apachemod-negotiation

Using mod_negotiation to serve webp if the UA requests it


Is it possible to use mod_negotiation to serve up a webp image if the browser supports it, and a jpg otherwise?

For instance, if I link to an image with the path /images/test, it serves the image found at /images/test.webp if the UA knows about webp, or jpg otherwise?

I've tried poking around, but it seems that the Accept headers in Chrome at least look like Accept:*/*, rather than specifying the image type.

If this isn't the way to do it, has anyone got any other suggestions?


Solution

  • For serving WebP images, I use a rewrite rule in nginx that checks for the existence of the file and support for WebP images. I ported it over to Apache mod_rewrite since the OP mentioned mod_negotiation. The rewrite looks for a User Agent containing the word "chrome" and than checks for a file with a .webp extension with the same name and path as the .jpg or the .png file and if so serves the WebP file. The rewrite rule is a bit kludgy but it gets the job done.

    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 luxury of being able to load my photos in via JavaScript after I can detect the support for WebP in the browser instead of relying on the user agent string. If WebP support exists than I set a cookie before I begin loading in my images. Therefore instead of this RewriteCond

    RewriteCond %{HTTP_USER_AGENT} (chrome) [NC]
    

    I would use this

    RewriteCond %{HTTP_COOKIE} supports_webp