问题:
我使用Nginx在浏览器中检测webp支持:
# Check if client is capable of handling webp
map $http_accept $webp_suffix {
default "";
"~*webp" ".webp";
}
后面几行我在下面的配置中使用这个变量:
location ~ ^/imgs/([0-9]*)/(.*?)(..+)$ {
add_header X-webp $webp_suffix;
try_files /imgs/$1$webp_suffix /imgs/$1$3 =404;
}
即使两个文件都存在,它总是导致e404,
try_files /imgs/$1$webp_suffix /imgs/$1$3 =404;
到
try_files /imgs/$1$3 /imgs/$1$webp_suffix =404;
在这逻辑中我漏掉了什么?
nginx.conf以重现:
events {
use epoll;
worker_connections 128;
}
http {
# Check if client is capable of handling webp
map $http_accept $webp_suffix {
default "";
"~*webp" ".webp";
}
server {
listen *:8888;
server_name test;
root /srv;
location ~ ^/imgs/([0-9]*)/(.*?)(..+)$ {
add_header X-webp $webp_suffix;
try_files /imgs/$1$webp_suffix /imgs/$1$3 =404;
}
}
}
try_files /imgs/$1$webp_suffix /imgs/$1$3 =404;
到:
try_files /imgs/$1.webp /imgs/$1$3 =404;
add_header X-webp $webp_suffix;
答案1:
map
包含在location
和try_files
语句之间计算的正则表达式。
解决方案是使用命名捕获:
例如:
location ~ ^/imgs/(?<prefix>[0-9]*)/(.*?)(?<suffix>..+)$ {
add_header X-webp $webp_suffix;
try_files /imgs/$prefix$webp_suffix /imgs/$prefix$suffix =404;
}
相关文章