0

I'm having some trouble getting the formatting of this right. I want to use sub_filter to insert a CloudFlare script in all pages:

sub_filter '</BODY>'
'<script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "aaabbbccc55dd"}'></script>
</BODY>
';

Who can help me sort out the various single and double quotes so this will work? (Or is there a way I can escape them?)

1 Answer 1

1
+50

Nginx ngx_http_sub_module module syntax is :

sub_filter string replacement;

In nginx strings may be inputted with­out quotes unless they include blank spaces, semi­colons or curly braces. When those characters are present they need to be escaped with back­slash­es or the strings need to be enclosed in single/​double quotes. (Vari­ables in quoted strings are going to be expand­ed unless the $ is escaped.)

You can thus simply escape the spaces (and don't quote the string):

sub_filter </BODY> <script\ defer\ src="https://static.cloudflareinsights.com/beacon.min.js"\ data-cf-beacon='{"token":\ "aaabbbccc55dd"}'></script>\ </BODY>;

Escaping the quotes should be redundant but doing so shouldn't be harmful either:

sub_filter </BODY> <script\ defer\ src=\"https://static.cloudflareinsights.com/beacon.min.js\"\ data-cf-beacon='\{\"token\":\ \"aaabbbccc55dd\"}\'></script>\ </BODY>;

or, you can quote the strings with either single or double quotes and then escape those single or double quotes (with a \) whenever they occur in your strings:

sub_filter '</BODY>' '<script defer src=\'https://static.cloudflareinsights.com/beacon.min.js\' data-cf-beacon=\'{"token": "aaabbbccc55dd"}\'></script> </BODY>';
sub_filter "</BODY>" "<script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{\"token\": \"aaabbbccc55dd\"}'></script> </BODY>";

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .