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.

pasuna
  • 1,405
  • 2
  • 15
  • 21

1 Answers1

54

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;
}
pasuna
  • 1,405
  • 2
  • 15
  • 21
  • 1
    IndexHeadInsert is used in Apache I am looking for a similar command in NGINX – TheBlackBenzKid Dec 07 '14 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](http://serverfault.com/a/223526/138913)) and look for `--with-http_sub_module`. – JoshStrange Apr 14 '15 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 '17 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? – EgoPingvina Jul 16 '20 at 13:44