40

Is there a way to inject a few lines of script etc. for each served php/html/etc. page? For example some custom javascript after -tag?

I know, you should be able to use lua in nginx but is there a better solution?

I am running multiple different web application behind the nginx, so it feels proper way to do this. I don't have access source code for each application and maintaining those would be cumbersome.

1 Answer 1

56

I found the way to do this: http://nginx.org/en/docs/http/ngx_http_sub_module.html

location / {
    sub_filter </head>
        '</head><script language="javascript" src="$script"></script>';
    sub_filter_once on;
}
4
  • 1
    IndexHeadInsert is used in Apache I am looking for a similar command in NGINX Dec 7, 2014 at 23:27
  • 2
    Quick note, this module is not built by default (as the linked article states) so your install may not have it. You can see if you have it with: nginx -V which "will list all the configured modules" (Source) and look for --with-http_sub_module. Apr 14, 2015 at 23:26
  • 11
    If the content is gzipped the substitution won't work. For that, add proxy_set_header Accept-Encoding "";, which tells the backend that compression isn't allowed in a response.
    – acdcjunior
    Apr 12, 2017 at 20:12
  • 1
    But what if I want to inject base at the start of head and head can contain some attributes, which I don't know in advance? Jul 16, 2020 at 13:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.