Last active
May 25, 2024 17:02
-
-
Save uhop/9177153 to your computer and use it in GitHub Desktop.
Serving WEBP with nginx conditionally.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
user www-data; | |
http { | |
## | |
# Basic Settings | |
## | |
sendfile on; | |
tcp_nopush on; | |
tcp_nodelay on; | |
# IMPORTANT!!! Make sure that mime.types below lists WebP like that: | |
# image/webp webp; | |
include /etc/nginx/mime.types; | |
default_type application/octet-stream; | |
gzip on; | |
gzip_disable "msie6"; | |
## | |
# Conditional variables | |
## | |
map $http_accept $webp_suffix { | |
default ""; | |
"~*webp" ".webp"; | |
} | |
## | |
# Minimal server | |
## | |
server { | |
listen 80 default_server; | |
listen [::]:80 default_server ipv6only=on; | |
root /usr/share/nginx/html; | |
index index.html; | |
# Make site accessible from http://localhost/ or whatever you like | |
server_name localhost; | |
location ~* ^/images/.+\.(png|jpg)$ { | |
root /home/www-data; | |
add_header Vary Accept; | |
try_files $uri$webp_suffix $uri =404; | |
} | |
} | |
} |
@uhop
I create .webp files statically using a utility, I don't want to deal with possible overwrites.
If you serving a WordPress site, you may use Warp iMagick plugin with your nginx configuration.
Can I use this without .webp files?
@h2kyaw You can. See the comments above explaining my approach. But you can obviously update the recipe to suit your needs.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@GariStar I am not sure your approach is correct as is:
rewrite
. See the referenced blog post.nopng
, because it misses a dot in it. And it has some other minor problems.The reason why in my original code I add a suffix instead of manipulating names is actually simple: because I use
webp
forpng
andjpg
removing the original extensions opens up for a potential name clash. Compare:image.png
⇒image.png.webp
image.jpg
⇒image.jpg.webp
with:
image.png
⇒image.webp
image.jpg
⇒image.webp
I create
.webp
files statically using a utility, I don't want to deal with possible overwrites.On top of that my actual code (not the toy one in the example) can serve multiple compressions:
brotli
,zopfli
, andgzip
for text files + original uncompressed files, if the precompressed versions are missingwebp
,zopflipng
, andpng
forpng
-style imageswebp
,guetzli
, andjpg
forjpg
-style imagesNowadays I am considering adding avif to the list.
That's why a name manipulation is not a priority to me.
If it is important it is possible not only update file names but serve files from:
Doing that will help with potential name clashes as well.