Nginx下lua根据客户端ip进行分发

公司的线上环境分为预发布和正式两个部分。

其实两个部分是公用一个Nginx前端的。

这样怎么分发呢?

lua即可,如果是公司来的某个固定ip,则分发到预发布,如果不是,就走正式环境。这样测试就简单多了,运维统一设置一个无线wifi,接入这个wifi就走某个固定ip,到的全是预发布环境,不用这个wifi就走正式环境,非常方便测试。

用lua进行分发:

 1location / {  
 2    content_by_lua '
 3            myIP = ngx.req.get_headers()["X-Real-IP"]
 4            if myIP == nil then
 5                myIP = ngx.req.get_headers()["x_forwarded_for"]
 6            end
 7            if myIP == nil then
 8                myIP = ngx.var.remote_addr
 9            end
10            if myIP == "公司出口IP" then
11                ngx.exec("@client")
12            else
13                ngx.exec("@client_test")
14            end
15        ';
16} 
17
18location @client{  
19    proxy_next_upstream     error timeout;
20    proxy_redirect          off;
21    proxy_set_header        Host $host;
22    #proxy_set_header        X-Real-IP $remote_addr;
23    proxy_set_header        X-Real-IP $http_x_forwarded_for;
24    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
25    client_max_body_size    100m;
26    client_body_buffer_size 256k;
27    proxy_connect_timeout   180;
28    proxy_send_timeout      180;
29    proxy_read_timeout      180;
30    proxy_buffer_size       8k;
31    proxy_buffers           8 64k;
32    proxy_busy_buffers_size 128k;
33    proxy_temp_file_write_size 128k;
34    proxy_pass http://client;
35
36}
37location @client_test{  
38    proxy_next_upstream     error timeout;
39    proxy_redirect          off;
40    proxy_set_header        Host $host;
41    #proxy_set_header        X-Real-IP $remote_addr;
42    proxy_set_header        X-Real-IP $http_x_forwarded_for;
43    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
44    client_max_body_size    100m;
45    client_body_buffer_size 256k;
46    proxy_connect_timeout   180;
47    proxy_send_timeout      180;
48    proxy_read_timeout      180;
49    proxy_buffer_size       8k;
50    proxy_buffers           8 64k;
51    proxy_busy_buffers_size 128k;
52    proxy_temp_file_write_size 128k;
53    proxy_pass http://client_test;
54} 

Lua与redis结合应用于nginx的动态upstream
如何禁止libvirtd自带的dnsmasq启动
comments powered by Disqus