9

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

 7 months ago
source link: https://bajie.dev/posts/20240123-lua_ip_forward/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

2024-01-23 1 分钟阅读

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

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

这样怎么分发呢?

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

用lua进行分发:

location / {  
    content_by_lua '
            myIP = ngx.req.get_headers()["X-Real-IP"]
            if myIP == nil then
                myIP = ngx.req.get_headers()["x_forwarded_for"]
            end
            if myIP == nil then
                myIP = ngx.var.remote_addr
            end
            if myIP == "公司出口IP" then
                ngx.exec("@client")
            else
                ngx.exec("@client_test")
            end
        ';
} 

location @client{  
    proxy_next_upstream     error timeout;
    proxy_redirect          off;
    proxy_set_header        Host $host;
    #proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Real-IP $http_x_forwarded_for;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    client_max_body_size    100m;
    client_body_buffer_size 256k;
    proxy_connect_timeout   180;
    proxy_send_timeout      180;
    proxy_read_timeout      180;
    proxy_buffer_size       8k;
    proxy_buffers           8 64k;
    proxy_busy_buffers_size 128k;
    proxy_temp_file_write_size 128k;
    proxy_pass http://client;

}
location @client_test{  
    proxy_next_upstream     error timeout;
    proxy_redirect          off;
    proxy_set_header        Host $host;
    #proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Real-IP $http_x_forwarded_for;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    client_max_body_size    100m;
    client_body_buffer_size 256k;
    proxy_connect_timeout   180;
    proxy_send_timeout      180;
    proxy_read_timeout      180;
    proxy_buffer_size       8k;
    proxy_buffers           8 64k;
    proxy_busy_buffers_size 128k;
    proxy_temp_file_write_size 128k;
    proxy_pass http://client_test;
} 

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK