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

如何在Nginx中正确获取查询参数值?解决多参数获取失效问题

解决Nginx中获取多个查询参数值的问题

Hey there! Let's figure out why your current Nginx config only grabs the attribute parameter and not category, plus walk you through the most reliable ways to get both values.

最简便的方案:用Nginx内置变量直接获取

Nginx has built-in variables specifically for query parameters that let you skip writing custom regex entirely. For any parameter named param, you can access its value directly using $arg_param—it's that simple.

For your example URL example.com/?attribute=2&category=1, you can fetch both values like this:

# 直接获取两个参数的值,无需正则匹配
set $attribute $arg_attribute;
set $category $arg_category;

This method is way more maintainable and avoids weird edge cases with regex matching. It also works no matter what order your parameters are in the URL.

为什么你的原有代码只拿到了attribute?

Your current regex for attribute=(\d+) works, but the issue with the category match might be that your regex doesn't account for other parameters surrounding it. For example, if category comes after attribute, the plain category=(\d+) regex should still match, but it can fail if there are extra characters or unexpected parameter ordering.

If you still want to use regex (though the built-in variable method is strongly recommended), adjust your regex to match anywhere in the full query string:

if ($args ~* "attribute=(\d+)") {
    set $attribute $1;
}
# 修改正则,确保能匹配到任意位置的category参数
if ($args ~* "category=(\d+)") {
    set $category $1;
}

The ~* flag makes the match case-insensitive (optional but handy), and the regex will now find the category parameter no matter where it appears in the query string.

总结

Stick with the $arg_ prefix variables whenever you can—they're purpose-built for this exact use case and eliminate regex-related headaches. If you need to validate parameter formats (like ensuring values are digits), you can combine the built-in variable with a regex check later on.

内容的提问来源于stack exchange,提问作者Liza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:19:39