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

Filter for location including query in nginx

· 52CE 我爱测

This is a super ugly workaround due to a specific customer request. Default setup: using proxy_pass to the backend like so (i've removed useless items) server{ server_name customer.mysite.com; location / { proxy_pass http://backe…

问题原文

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

This is a super ugly workaround due to a specific customer request.

Default setup: using proxy_pass to the backend like so (i've removed useless items)

server{
  server_name customer.mysite.com;
  location / {
    proxy_pass http://backend.mysite.com/[customerId];
  }
}

So far so easy, everything gets rewritten and we are fine. However, now the requirement is that if the customer comes without any query parameters, we should add some.

My initial thought was using a second rule with location = / for an exact match, but the docs do not indicate that this method cares about query params at all.

So, is there some way to do what I need in nginx or do I have to find some other way?

已采纳解答

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

To test for the absence of a query string, you can compare the $args variable with an empty string using an if block. To apply this rule to the URI / only, place it inside a location = / block.

For example:

location / {
    proxy_pass http://backend.example.com/customerId/;
}
location = / {
    if ($args = "") { rewrite ^ /?query=foo last; }
    proxy_pass http://backend.example.com/customerId/;
}

See this caution on the use of if.

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

资料来源与适用范围

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

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

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