大网数据广告活动
服务器运维问答

try_files doesn't use variables from regex and map

· 52CE 我爱测

I'm trying to conditionally serve .webp images to supported clients. The images are stored like image.jpg and image.jpg.webp in the same folder. I can't get try_files to do what I think it should to. When I use $1$webp_suffix as …

问题原文

原帖链接 · Peerke · CC BY-SA 4.0

I'm trying to conditionally serve .webp images to supported clients. The images are stored like image.jpg and image.jpg.webp in the same folder.

I can't get try_files to do what I think it should to. When I use $1$webp_suffix as the location it fails and also does not try the second location.

In nginx.conf I set $webp_suffix like so:

http {
    map $http_accept $webp_suffix {
        default "";
        "~*webp"    ".webp";
    }
    include /opt/local/etc/nginx/vhosts/*;
}

But when I try to use the suffix in my virtual host I get an error 404.

server {
  
    listen 443 ssl;
    server_name my.example.com;

    # allow /data/ and /data/343/ as public URL
    location ~ ^/data/[0-9/]*(.*)$ {
        expires 365d;
        add_header Cache-Control "public, no-transform";
        # Serve webp images when available and supported
        location ~ ^/data/[0-9/]*(.+\.(png|jpg))$ {
            add_header Vary Accept;
            alias /local/path/httpdocs/data/;
            try_files $1$webp_suffix $1 =404;
        }
        alias /Users/r/Sites/cms/httpdocs/data;
        try_files /$1 =404;
    }
}

Everything works when I remove $1$webp_suffix, so the paths and such seem correct.

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 4.0

The problem is $1. It gets overwritten each time Nginx evaluates a regular expression. The expression $1$webp_suffix causes Nginx to evaluate the regular expression in the map statement, which simultaneously causes $1 to become an empty string.

Use a named capture in the location statements.

For example:

location ~ ^/data/[0-9/]*(?<filename>.*)$ {
    expires 365d;
    add_header Cache-Control "public, no-transform";
    # Serve webp images when available and supported
    location ~ \.(png|jpg)$ {
        add_header Vary Accept;
        root /local/path/httpdocs/data/;
        try_files /$filename$webp_suffix /$filename =404;
    }
    root /Users/r/Sites/cms/httpdocs/data;
    try_files /$filename =404;
}

Also, you should be using root instead of alias.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2021-04-28)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。