nginx rewrite url with if and arg

JCats asked:

Trying to use a wildcard redirect here but unable to figure out what to set for the wildcard, example:

URL: example.com/search?q=broccoli
Redirect to: example.com/?s=broccoli

broccoli can be anything

code:

location /search {
  if ($arg_q) {
  return 301 https://example.com/?s=$1;
  }
}

The result is example.com/?s=

not sure what ‘variable’ I have to use in place of $1

I was thinking maybe having to do something like

location /search {
  if ($arg_q = (.*)) {
  return 301 https://example.com/?s=$1;
  }
}

but no luck there either.

My answer:


If you’re trying to use the value of q, then you just use that value, the same as you already did!

location /search {
    if ($arg_q) {
        return 301 https://example.com/?s=$arg_q;
    }
}

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.