Home > Net >  webp fallback jpg using htaccess
webp fallback jpg using htaccess

Time:02-27

I use webp format by default in images, I want to show the jpg version in browsers that do not support webp.

I want to do this using htaccess, my code converts jpg to webp, how can I reverse this?

<IfModule mod_rewrite.c>
  RewriteEngine On

  RewriteCond %{HTTP_ACCEPT} image/webp

  RewriteCond %{DOCUMENT_ROOT}/$1.webp -f

  RewriteRule (. )\.(jpe?g|png|gif)$ $1.webp [T=image/webp,E=REQUEST_image]
</IfModule>

<IfModule mod_headers.c>

  Header append Vary Accept env=REQUEST_image
</IfModule>

<IfModule mod_mime.c>
  AddType image/webp .webp
</IfModule>

CodePudding user response:

So you're linking to .webp images and you want to serve the corresponding .jpg image if the user does not support image/webp type images, but presumably testing whether the corresponding .jpg image actually exists first before trying to serve it...

RewriteCond %{HTTP_ACCEPT} !image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.jpg -f
RewriteRule (. )\.webp$ $1.jpg [T=image/jpeg,E=REQUEST_image]

Testing whether the .jpg image exists maybe unnecessary if the user-agent does not actually support webp images anyway. Which is preferable... some kind of image display issue or a 404? Then again, if the .jpg image always exists then the file check is redundant anyway.

  • Related