You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx WebP图片Rewrite规则报错:location指令参数数量无效

Nginx WebP图片Rewrite规则报错:location指令参数数量无效

嘿,我一眼就揪出问题啦!你这条location规则里的正则表达式写错了,这才让Nginx抛出「invalid number of arguments in 'location'」的错误。

具体来说,你写的location ~* ^(/. )\.(jpg|jpeg|jpe|png|gif)$里,^(/. )这部分有语法问题——这里的空格完全多余,而且会让Nginx误以为你给location传了多个参数,自然就报错了。你应该把它改成^(/.+),这个正则才是正确匹配「任意以/开头的路径」的写法。

下面是修正后的完整配置:

location ~* ^(/.+)\.(jpg|jpeg|jpe|png|gif)$ {
    add_header Vary Accept;

    if ($http_accept ~* "webp"){
        set $imwebp A;
    }

    if (-f $request_filename.webp) {
        set $imwebp  "${imwebp}B";
    }

    if ($imwebp = AB) {
        rewrite ^(.*) $1.webp;
    }
}

改完之后,你可以用nginx -s reload命令重启Nginx服务,应该就不会再报这个错误了。要是想验证WebP是否生效,用浏览器开发者工具看响应头,或者用curl模拟带Accept: image/webp的请求,看看是不是返回了WebP格式的图片就行。

备注:内容来源于stack exchange,提问作者Gavin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.20 06:58:02