As nobody has answered I can give you the "how" but only from an .htaccess
perspective.
Hopefully that is enough to allow you to apply the same rules in IIS.
.htaccess way of doing it
AddType image/webp .webp
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_FILENAME}.webp -f
RewriteRule ^/?(.+?)\.(jpe?g|png)$ /$1.$2.webp [NC,T=image/webp,E=EXISTING:1,E=ADDVARY:1,L]
<IfModule mod_headers.c>
<FilesMatch "(?i)\.(jpe?g|png)$">
Header append "Vary" "Accept"
</FilesMatch>
</IfModule>
</IfModule>
Steps performed
- What we do is check the headers the browser sends with
%{HTTP_ACCEPT} image/webp
I think that can be written as
<add input="{HTTP_ACCEPT}" pattern="image/webp" ignorecase="false">
in IIS (sorry that is the extent of my IIS knowledge without a live server to play on!)
Then we check that the request exists (the original file exists) on the next line (this is because technically it should 404 if the original image was a jpg
and the request was for a jpg
, you may decide to handle this differently).
Then we check that we have the same file but with .webp
extension on the end (our converted image)
If the file exists with a .webp
(step 3) extension and the browser accepts image/webp
(step 1) we rewrite the request and add .webp
to the end of the file name that the system will use to locate the file, we then return the type image/webp
so that a browser knows what to do with it.
Finally in the last section we send back the header vary accept so the browser knows it is ok to use the image with a different mime type than expected.
In order to use the above method it relies on you placing the files in the same directory and naming them the same but with .webp
on the end.
E.g.
https://example.com/img/imagefolder/myimage.jpg
would need a webp file named:
https://example.com/img/imagefolder/myimage.jpg.webp
to work.
Obviously as these are rewrites on the server side this should hopefully preserve your link juice (but bear in mind you are still sending a different file type so it may not work), but at least your end users will be happy.