openresty 根据系统环境变量配置proxy_pass的URL

1,890 阅读1分钟

假设你有多个环境.

  • integ2
  • integ3
  • integ4

你的对外服务域名为:

  • integ2.app.com
  • integ3.app.com
  • integ4.app.com

你有一个静态资源服务器,域名分别为

  • integ2.resource.com
  • integ3.resource.com
  • integ4.resource.com

需求如下: 如果前端请求静态资源的URL是integ2.resource.com/static, 但是我们需要修改这个URL为integ2.resouce.com/resource/st…

请求流程为

client -> integ2.app.com/static/what-I-want -> integ2.resource.com/resource/static/what-I-want

nginx关键配置如下

  1. 首先你要把环境变量(根据你的需求)注入nginx服务器,我目前是使用k8s的ingress-nginx,环境变量为 ENV
  2. 在openresty中使用这个环境变量ENV

    1.在main block设置

     pid /tmp/nginx.pid;
    
     daemon off;
    
     worker_processes 2;
    
     worker_rlimit_nofile 523264;
    
     worker_shutdown_timeout 10s ;
    
     env ENV; #这里表示nginx配置中可以使用这个环境变量
    
     events {
         multi_accept        on;
         worker_connections  16384;
         use                 epoll;
     }
     
     http {
     	...
         ...
         server {
     		...
     	}
     }
    

    2.在location中使用lua语法获取

    localtion ^~ /static/ { 
    
       #通过set_by_Lua动态设置url地址https://integ2.resource.com(lua拼接字符串)
       set_by_lua $domain 'return "https://"..os.getenv("ENV")..".resouce.com"'; 
       #因为proxy_pass设置了变量,你需要把完整的URL告诉proxy_pass!!
       proxy_pass $domain/resource$request_uri;      
    
    }
    

这样做的好处是什么呢?

当你需要管理多个环境,而且你每个环境的系统架构都是一样,在这种情况下,你只需要维护一个配置文件,唯一的区别就是环境名称不一样,在这个场景之中,就是integ2 integ3 integ4 preprod prod 等等。如果你需要更新配置的时候,就不需要关心域名信息了。只需要关心具体的事情,如正则匹配,rewrite,proxy_pass,cache-control,location等等

知识点如下

  • k8s注入环境变量
  • nginx使用环境变量(env XXX)
  • openresty自定义变量(set_by_lua $v 'xxxx')
  • proxy_pass(当你在这里直接使用环境变量时,你需要明确告诉他完整的URL,nginx不会自动拼接)
  • 另外在ingress-nginx,我使用了configmap维护nginx的配置,好处是,当使用kubectl apply -f 更新时,nginx会自动reload

相关URL