CT_WM
CT_WM

Reputation: 11

Nginx - Rewrite multiple parameters

This may or may not be possible but thought I would ask.

We had recently changed some of the query parameters and wanted to 301 redirect the old version to the new version.

The old parameter scheme was categoryX=Y where X was some number and Y was some number (an example being category56=112). The new version just drops off the X so we have category=112. Now, this seems fairly simple enough to do if there is either a known number of parameters or a single parameter. However, there can be a variable number of these parameters. For example:

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

I'm guessing there isn't a way to basically "for each" through the parameters and if a regex matches category(0-9+)=(0-9+) to change it to category=(0-9+)?

Upvotes: 1

Views: 1144

Answers (1)

Dayo
Dayo

Reputation: 12775

You can loop through your args but you will need the 3rd party Nginx Lua module which is also part of the Openresty Bundle.

With that in place, something along these lines should do the job ...

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 
     ';
 }

Upvotes: 1

Related Questions