Home > Software engineering >  Using regex capture groups from both the location and rewrite?
Using regex capture groups from both the location and rewrite?

Time:12-30

Given some example like:

location ~ ^/([\d] )/ {
    rewrite ^/[\d] /([\d] )/(.*)$ #replacement
    
    proxy_pass https://httpbin.org/anything/$1/$2/$3 # ?

}

What would the capture groups be? Does nginx replace them? Merge them? Would I have 3 capture groups in that case? What would the ordering be?

It's unclear to me how I would reference each of the 3 capture groups above.

The final place I'm referencing the capture groups is in a proxy_pass.

CodePudding user response:

The numeric captures are reset each time Nginx evaluates another regular expression.

The numeric captures from the location expression are lost by the time the proxy_pass statement is evaluated. Only $1 and $2 are defined, and these are taken from the rewrite expression.

To make a capture persist across multiple regular expressions, give it a name using the (?<name>...) syntax.

For example:

location ~ ^/(?<name>[\d] )/ {
    rewrite ^/[\d] /([\d] )/(.*)$ ...;        
    proxy_pass https://httpbin.org/anything/$name/$1/$2;
}
  • Related