diff --git a/gixy/directives/block.py b/gixy/directives/block.py index b7549b4..b2c8006 100644 --- a/gixy/directives/block.py +++ b/gixy/directives/block.py @@ -4,7 +4,7 @@ from functools import cached_property from gixy.directives.directive import Directive, MapDirective -from gixy.core.variable import Variable +from gixy.core.variable import Variable, compile_script from gixy.core.regexp import Regexp @@ -165,6 +165,7 @@ def needs_anchor(self): class IfBlock(Block): nginx_name = "if" self_context = False + provide_variables = True def __init__(self, name, args): super(IfBlock, self).__init__(name, args) @@ -184,6 +185,28 @@ def __init__(self, name, args): else: raise Exception('Unknown "if" definition, args: {0!r}'.format(args)) + @property + def is_regex(self): + return self.operand and self.operand in {"~", "~*", "!~", "!~*"} + + @cached_property + def variables(self): + if not self.is_regex: + return [] + + boundary = None + compiled_script = compile_script(self.variable) + if len(compiled_script) == 1: + boundary = compiled_script[0].regexp + + regexp = Regexp(self.value, case_sensitive=self.operand in {"~", '!~'}) + result = [] + for name, group in regexp.groups.items(): + result.append( + Variable(name=name, value=group, boundary=boundary, provider=self) + ) + return result + def __str__(self): return "{name} ({args}) {{".format(name=self.name, args=" ".join(self.args)) diff --git a/tests/directives/test_block.py b/tests/directives/test_block.py index b4ff4bb..1187cb7 100644 --- a/tests/directives/test_block.py +++ b/tests/directives/test_block.py @@ -103,7 +103,7 @@ def test_if(): assert isinstance(directive, IfBlock) assert directive.is_block assert not directive.self_context - assert not directive.provide_variables + assert directive.provide_variables assert directive.variable == '$some' assert directive.operand is None assert directive.value is None diff --git a/tests/plugins/simply/http_splitting/if_block.conf b/tests/plugins/simply/http_splitting/if_block.conf new file mode 100644 index 0000000..413615d --- /dev/null +++ b/tests/plugins/simply/http_splitting/if_block.conf @@ -0,0 +1,7 @@ +server { + server_name example.com; + + if ($uri ~* ^/echo/(.*)$) { + return 301 $1; + } +} diff --git a/tests/plugins/simply/http_splitting/if_block_fp.conf b/tests/plugins/simply/http_splitting/if_block_fp.conf new file mode 100644 index 0000000..469eca8 --- /dev/null +++ b/tests/plugins/simply/http_splitting/if_block_fp.conf @@ -0,0 +1,7 @@ +server { + server_name example.com; + + if ($request_uri ~* ^/echo/(.*)$) { + return 301 $1; + } +}