Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx: how to get url args which contain dash?

Tags:

nginx

I'm using nginx variable $arg_ to get url args.

But I find if the url is like 'http://foobar.com/search?field-keywords=foobar', $arg_field_keywords or $arg_field-keywords don't work.

Can I get field-keywords with $arg_?

Thanks in advance.

like image 995
jasonz Avatar asked Sep 26 '22 16:09

jasonz


2 Answers

While lua may work, we have nginx without lua support. Googling around I found the following answer from the upstream developer

While this may currently work, I wouldn't recommend relying on this - as this is rather a bug than a desired behaviour. This will stop working as long as support for multiple variables will be added to map.

Instead, I would recommend to use regexp-based parsing of the $args variable as Francis suggests. This can be done trivially with map, like this:

map $args $param_with_dash {
    "~(^|&)param-name=(?<temp>[^&]+)"  $temp;
}

Ref: https://marc.info/?l=nginx&m=141589036701879&w=2

like image 85
pva Avatar answered Sep 30 '22 01:09

pva


I had found article, that has a little trick to deal with your problem.

TLDR:

You can remap variables with complex names by using the map module as follows:

map $is_args $http_x_origin {
  default $http_x-origin;
}

The trick is that map does not fully parse its arguments. The syntax is: map A X { default Y; }, with:

  • A any variable, preferably one that does not trigger much internal processing (since nginx configs are declarative, using a variable evaluates it). I use $is_args because it’s cheap to calculate.
  • X is the name for the new variable you’ll be creating, i.e. the map target.
  • Y is the name of the variable you want to access. At this point, it can contain dashes, because map does its own parsing.

I guess it might work with $args_ too.

like image 26
Sergey Chizhik Avatar answered Sep 29 '22 23:09

Sergey Chizhik