如何在我的nginx.conf中包含一个javascript文件

时间:2017-08-04 00:54:43

标签: nginx

我正在尝试通过nginx向反向代理网站添加一段Javascript代码。

特别是,我有一个sub_filter规则可以这样工作:

sub_filter </head>
  '</head><script language="javascript">
     console.log("hello world")
   </script>';

我有没有办法将这个脚本重构为它自己的文件并从那里加载它。类似的东西:

sub_filter </head>
  '</head>$load_script_from('/src/tracking')';

或者这是不可能的,我应该使用gulp从一堆其他文件中编译我的nginx.conf吗?

这是我的完整nginx.conf

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {

    server {
        listen 80;
        server_name localhost;

        location / {

            sub_filter </head>
            '</head><script>console.log("hello world")</script>';

            proxy_pass 10.1.1.1:80;
            proxy_set_header Accept-Encoding "";
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我使用Openresty解决了这个问题,它允许你在lua中使用nginx。我保存了一个注入脚本,并使用set_by_lua_block将文件加载到变量中。

set_by_lua_block $injection_script {
  local f = io.open("/path/to/file.js", "rb")
  local content = f:read("*all")
  f:close()
  return content
}

sub_filter '</head>' "<script>${injection_script}</script></head>";