【问题标题】:How to rewrite a path, forward parameters and add parameters?如何重写路径、转发参数和添加参数?
【发布时间】:2016-09-08 08:37:46
【问题描述】:

This SO disucssion 表示在使用return 重写 url 时转发参数,代码应类似于此

location /path/to/resource {
  return 301 /some/other/path/$is_args$args;   
}

到目前为止,一切都很好。但是如何在查询字符串中添加任意新参数呢?例如id=1

解决方案必须至少涵盖以下三种情况:

  1. 原始请求没有查询参数
  2. 原始请求有查询参数,但没有添加参数
  3. 原始请求中已经添加了查询参数

【问题讨论】:

    标签: nginx nginx-location


    【解决方案1】:

    要重写路径,您可以使用 rewrite 关键字,例如

    location /path/to/resource {
    rewrite /some/other/path/$is_args$args;   
    }
    

    转发附加的参数 $args 将附加查询参数(如果存在),如果没有传递查询参数,则为空。

    用于有条件地添加新参数,例如 id=1 那么 if 构造可以在如下位置使用:

    location /path/to/resource {
    if($args !~* "id"){
    rewrite /some/other/path/$is_args$args&id=1;  
    } 
    }
    

    如果传入的 url 中不存在 'id' 字段,上面将附加该字段。

    【讨论】:

    • 如果没有查询参数会怎样?它不会以“/some/other/path/?&id=1”的形式出现吗?
    • True.. 但我想说的是你可以设置多个 if 条件来检查 $args 是否有任何值,并且它们相应地形成了重写 url
    猜你喜欢
    • 2018-10-05
    • 1970-01-01
    • 2010-11-10
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    相关资源
    最近更新 更多