用Lapis工程创建Openresty正向代理服务

2.4k 词

作者:糖果

正文:

利用Openresty服务创建一个正向代理服务器,最开始是想在Lapis创建的工程下直接创建,基本的配置如下面的代吗:

创建一个Lapis工程:

lapis new

然后在配置文件里加入,正向代理的配置。

worker_processes ${{NUM_WORKERS}};
error_log stderr notice;
daemon off;
pid logs/nginx.pid;

events {
  worker_connections 1024;
}

http {
  include mime.types;
  default_type  application/octet-stream;

  log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

  access_log  logs/access.log  main;

  server {
    resolver 114.114.114.114;
    resolver_timeout 15s;

    listen ${{PORT}};
    lua_code_cache ${{CODE_CACHE}};

    location / {
        default_type text/html;
        proxy_pass $scheme://$host$request_uri;
        #proxy_pass http://$host$request_uri;
        proxy_set_header Host $http_host;

        proxy_buffers 256 8k;
        proxy_max_temp_file_size 0;

        proxy_connect_timeout 30;

        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 301 1h;
        proxy_cache_valid any 1m;

      content_by_lua '
        --require("lapis").serve("app")
      ';
    }
  }

启动Lapis代理,配置FF的代理选项。打开浏览器后发现,可以载入网站的图标,但是正文无法显示出来,返回结果被Lapis拦截了。

然后,我向群里的朋友 ,求了一份,nginx的正向代理的配置,然后用纯nginx的方式,启动正向代理,代码如下:

worker_processes 1;
error_log stderr notice;
daemon off;
pid logs/nginx.pid;

events {
  worker_connections 1024;
}

http {
  include mime.types;
  default_type  application/octet-stream;

  log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

  access_log  logs/access.log  main;
  server {
    resolver 114.114.114.114;
    resolver_timeout 15s;

    listen 0.0.0.0:8080;

    location / {
        default_type text/html;
        proxy_pass $scheme://$host$request_uri;
        #proxy_pass http://$host$request_uri;
        proxy_set_header Host $http_host;
        proxy_buffers 256 8k;
        proxy_max_temp_file_size 0;
        proxy_connect_timeout 30;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 301 1h;
        proxy_cache_valid any 1m;
    }
  }
}

然后用传统的方式运行nginx

nginx -p `pwd` conf/nginx.conf

重新刷新浏览器,OK,结果出现。

后记:

其实,浏览器无返回结果的根原因,不是因为用了lapis起动工程,而是在lapis创建的nginx.conf中,定义了content_by_lua,却没有做任何的返回处理,造成的返回了空白网页。

如果还想用lapis server的方式启动正向代理,就把下面的代码注释掉。

#content_by_lua '
#  --require("lapis").serve("app")
#';