Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
enabling apache to serve WebP image files if accepted by browser (and .webp files available)
# originally from https://groups.google.com/a/webmproject.org/group/webp-discuss/browse_thread/thread/196ac4ea705688d8
<IfModule mod_rewrite.c>
# TODO: don't forget to put
# AddType image/webp .webp
# in your mods-available/mime.conf
# (though this is optional because we're setting
# the mime type manually in the RewriteRule)
# Enable rewrite
RewriteEngine On
# Does browser support WebP?
RewriteCond %{HTTP_ACCEPT} \bimage/webp\b
# Capture image name
RewriteCond %{REQUEST_URI} (.*)(\.jpe?g|png)$
# if you don't have all jpg/png images available
# as webp then you want to uncomment the next line
# so apache first checks if there is a webp file
# otherwise leave it disabled as it removes the
# need to query the disk
#RewriteCond %{DOCUMENT_ROOT}%1.webp -f
# Route to WebP image
RewriteRule .* %1\.webp [L,T=image/webp]
</IfModule>
Owner

seeekr commented Apr 18, 2012

thinking the redirect should be a permanent one... would the browser then not send another request to the original jpg/png image when it encounters that url once again and ask for the webp version immediately / get that one from cache immediately? will have to check that.
for pages with lots of images this redirect version would not be acceptable if that were not the case. if caching works regardless, then this would be fine.

For some reason my Apache added an extra dot, so I had to remove "." from the RewriteRule to make it work. (If someone is having problems getting it to work.)

You should add some rules to add "Vary Accept" if Apache served the webp format, or the image could be cached on proxy or CDN in an incorrect format.

mzealey commented Oct 3, 2017

RewriteCond %{REQUEST_URI}  (.*)(\.jpe?g|png)$ 

is wrong as @tuhoojabotti noticed - pngs wont work like that. should be:

RewriteCond %{REQUEST_URI}  (.*)(\.(jpe?g|png))$ 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment