The addition before sub

Maxim Dounin mdounin at
Thu Jun 6 13:57:41 UTC 2013


On Thu, Jun 06, 2013 at 03:41:53PM +0200,  Witold Filipczyk wrote:

> Hello,
> I want to inject something before </body> and before </head>, but
> even if there is no </body>.
> So used add_after_body /after_body;
> /after_body returns the text </body>, so there is at least one
> </body> in the page.
> I wanted sub_filter to replace </body> to SOMETHING</body>, but the
> sub_filter is run before the addition_filter.
> Changing the order in modules doesn't help, because the sub_filter
> doesn't replace the text from subrequests.

Works fine here:

    location / {
        add_after_body /after.html; 
        sub_filter 'foo' 'bar';

$ cat main.html
this is main.html: foo
$ cat after.html
this is in after.html: foo
$ fetch -qo - 'http://localhost:8080/main.html'
this is main.html: bar
this is in after.html: bar

The explanation is simple: addition filter uses _subrequests_ to 
add text, and these subrequests are in turn processed by the whole 
filter chain, including the sub filter.  Hence order of sub and 
addition filters doesn't matter.

Most likely it doesn't work for you because /after_body have some 
default mime type not matched by sub_filter_types, see

> I have a few questions:
> How to replace two different substrings using sub_filter or something else?

As of now it's not possible.

> How to force sub_filter to replace text, even if it comes from the
> addition filter?

This works out of the box, see above.

Maxim Dounin

More information about the nginx-devel mailing list