Skip to content

Instantly share code, notes, and snippets.

@uhop
Last active November 3, 2023 12:09
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save uhop/9177153 to your computer and use it in GitHub Desktop.
Save uhop/9177153 to your computer and use it in GitHub Desktop.
Serving WEBP with nginx conditionally.
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;
}
}
}
@ddur
Copy link

ddur commented Aug 30, 2021

@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.

@h2kyaw
Copy link

h2kyaw commented Dec 25, 2021

Can I use this without .webp files?

@uhop
Copy link
Author

uhop commented Dec 25, 2021

@h2kyaw You can. See the comments above explaining my approach. But you can obviously update the recipe to suit your needs.

@ddur
Copy link

ddur commented Feb 18, 2022

BTW, WordOps Control Panel for Nginx Server and WordPress Sites is already configured for WebP and AVIF.

@pmochine

For example: picture.jpg => picture.webp and not picture.jpg.webp

Imagine uploading picture.jpg and picture.png into same directory. What would happen?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment