【问题标题】:Nginx - Rewrite multiple parametersNginx - 重写多个参数
【发布时间】:2016-09-29 15:33:36
【问题描述】:

这可能会也可能不会,但我想我会问。

我们最近更改了一些查询参数,想将旧版本 301 重定向到新版本。

旧的参数方案是categoryX=Y,其中X 是某个数字,Y 是某个数字(例如category56=112)。新版本刚刚删除了X,所以我们有了category=112。现在,如果存在已知数量的参数或单个参数,这似乎相当简单。然而,这些参数的数量可以是可变的。例如:

http://www.example.com/some_directory/index.shtml?category56=112
http://www.example.com/some_other_directory/index.shtml?category8=52&category11=2&other_param=12

我猜没有办法通过参数基本上“为每个”,如果正则表达式匹配 category(0-9+)=(0-9+) 将其更改为 category=(0-9+)

【问题讨论】:

  • 改为在您的应用中执行。这会容易得多。
  • 是的,我想的差不多(在应用程序中做)。想确保我没有遗漏一些明显的东西。

标签: regex redirect nginx


【解决方案1】:

你可以遍历你的参数,但你需要第三方 Nginx Lua 模块,它也是 Openresty Bundle 的一部分。

有了这些,按照这些思路的东西应该可以完成这项工作......

location /foo {
    rewrite_by_lua '
        local new_args = "exit"
        local exit = false
        local m, err = nil
        -- load arguments
        local args = ngx.req.get_uri_args()

        -- loop through arguments and rebuild
        for key, val in pairs(args) do
            -- stop loop if "abort" arg is found
            if key == "exit" then
                exit = "true"
                break
            end 
            m, err = ngx.re.match(key, "category(0-9+)")
            if m then
                 new_args = new_args .. "&category=" .. val
             else
                 new_args = new_args .. "&" .. key .. "=" .. val
             end
         end

        -- redirect if we have not been here before
         if exit == "false" then
            return ngx.redirect(ngx.var.scheme .. "://" .. ngx.var.host .. ngx.var.request_uri .. ngx.var.isargs .. new_args)
         end 
     ';
 }

【讨论】:

  • 谢谢,我认为我目前没有可用的模块,但会看看它是否可以使用。
  • ngx.var.request_uri更改为ngx.var.uringx.var.isargs更改为ngx.var.is_args
猜你喜欢
  • 2015-08-26
  • 1970-01-01
  • 2017-01-18
  • 2012-10-12
  • 2015-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
相关资源
最近更新 更多