openresty / replace-filter-nginx-module

Streaming regular expression replacement in response bodies
260 stars 68 forks source link

Dynamic regex match #12

Open Roycohen opened 9 years ago

Roycohen commented 9 years ago

Hi There, Is it possible to implement dynamic variables after matching a string. I'll explain: I need to replace a know regex but the value that I need to change is dynamic and comes from the regex. Example:

replacefilter "[(AV.*?)]" '${argAV$0}' g;

The above should find all matching regexes for [AV__] and replace it form the nginx arg_AV__. If, I find [AV_STAT] in the body then it should change it from the {arg_AV_STAT}. And if I have another [AV_DEFINE] then the value should be taken from the {arg_AV_DEFINE}.

I hope I make my self clear. Is there a way that this supported, and if not can you please guide me where to look in your code or or whether it is possible to modify your code and implement it?

BR, Roy

agentzh commented 9 years ago

@Roycohen It cannot be done in the current implementation though it's certainly possible to modify the current code base to support this. I think your configuration does not quite do what you want. It seems that you really need this instead (untested, of course):

replace_filter "\[(AV_[A-Z]+)\]" "${arg_$1}" g;

You'll need to call ngx_http_get_variable() to query nginx variables on the fly. Also, you need to re-evaluate the replacement string upon every match in the same request. I suggest adding a test to only do this when absolutely necessary so that we won't pay the price when the user does not use this feature.

Patches welcome :)

Roycohen commented 9 years ago

OK @agentzh, Can you please give me a starting point, where are the main functions that I need to modify? If I'll succeed I'll be glad to add a patch :)

agentzh commented 9 years ago

@Roycohen You need to patch the ngx_http_replace_body_filter function for calculating sub (i.e., the replacement string) and also most of the functions in the ngx_http_replace_script.c file for compiling and evaluating the replacement templates. Well, at least these functions.