1. 程式人生 > >Nginx有多級代理時,獲取使用者的真實IP地址

Nginx有多級代理時,獲取使用者的真實IP地址

在web伺服器前面設定代理伺服器時,從nginx模組中取$remote_addr值為上一級代理的IP地址,而非真實客戶端的IP地址。為了獲取真實客戶端IP地址,可以使用nginx自帶的realip模組。此模組可將真實客戶端IP地址設定進HTTP請求頭中,以便後端的web伺服器獲取。

下面是一級代理 nginx + nginx 時的設定步驟示例:

第一步:安裝realip模組

在nginx的安裝階段中的./configure時,需要帶上--with-http_realip_module,以將realip模組編譯進nginx

第二步:配置nginx.conf

在代理伺服器設定中新增proxy_set_header X-Real-IP $remote_addr;

如下:

location /.well-known/est/serverkeygen {
           proxy_pass http://127.0.0.1:61084;
           proxy_set_header   X-Real-IP   $remote_addr;
        }

在web伺服器設定中新增 set_real_ip_from 127.0.0.1; 其中127.0.0.1是代理伺服器地址,這裡是本機地址。

        location /.well-known/est {
            set_real_ip_from  127.0.0.1;
            est;
        }
第三步 在nginx模組中獲取IP地址
    ngx_int_t   key;
    ngx_http_variable_value_t *remoteAddress = NULL;
    ngx_str_set(&var_name, "remote_addr");
    key = ngx_hash_key(var_name.data, var_name.len);
    remoteAddress = ngx_http_get_variable(r, &var_name, key);
    if (remoteAddress == NULL || remoteAddress->
not_found == 1) { ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR); return; } ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0, "remote Addr(len:%d): %s", remoteAddress->len, remoteAddress->data);

// 怕什麼真理無窮,進一步有進一步的歡喜.