location ~* \.(png|jpe?g|gif)$ {
set $avif_image_path "";
if ($http_accept ~* "image/avif") {
set $avif_image_path "$uri.avif";
}
set $webp_image_path "";
if ($http_accept ~* "image/webp") {
set $webp_image_path "$uri.webp";
}
add_header Vary Accept;
try_files $avif_image_path $webp_image_path $uri =404;
}
worker_processes auto;
events {
worker_connections 1024;
multi_accept on;
}
http {
access_log /dev/stdout;
error_log /dev/stdout info;
charset utf-8;
server_tokens off;
sendfile on;
tcp_nodelay on;
tcp_nopush on;
include mime.types;
default_type application/octet-stream;
server {
listen 80;
root /usr/share/nginx/public;
index index.html index.xml;
location ~* \.(png|jpe?g|gif)$ {
set $avif_image_path "";
if ($http_accept ~* "image/avif") {
set $avif_image_path "$uri.avif";
}
set $webp_image_path "";
if ($http_accept ~* "image/webp") {
set $webp_image_path "$uri.webp";
}
add_header Vary Accept;
add_header X-Debug "avif: `$avif_image_path`, webp: `$webp_image_path`, uri: `$uri`";
try_files $avif_image_path $webp_image_path $uri =404;
}
}
}
if
исполняется только содержимое блока if.add_header
.try_files
не наследуется и исполняется только когда уловие if
ложно.location
.if
в контексте server
таких проблем нет.if
на уровень server
и всё заработает как ожидалось.server {
set $avif_image_path "";
if ($http_accept ~* "image/avif") {
set $avif_image_path "$uri.avif";
}
set $webp_image_path "";
if ($http_accept ~* "image/webp") {
set $webp_image_path "$uri.webp";
}
location ~* \.(png|jpe?g|gif)$ {
add_header Vary Accept;
try_files $avif_image_path $webp_image_path $uri =404;
}
if
и переписать на map
. map
:map $http_accept $avif_image_path {
default "";
~image/avif "$uri.avif";
}
map $http_accept $webp_image_path {
default "";
~image/webp "$uri.webp";
}
server {
# ...
location ~* \.(png|jpe?g|gif)$ {
add_header Vary Accept;
try_files $avif_image_path $webp_image_path $uri =404;
}
# ...
}