1

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+)?

2
  • Do it in your app instead. It would be much easier. Commented May 31, 2016 at 15:03
  • Yea, I kind of figured as much (doing it in the app). Wanted to make sure I wasn't missing something obvious. Commented Jun 1, 2016 at 19:55

1 Answer 1

1

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 
     ';
 }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, don't think I currently have that module available but will take a look at it to see if we can use it.
Change ngx.var.request_urito ngx.var.uri and ngx.var.isargs to ngx.var.is_args.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.