Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

用 Nginx 做跨城市代理:把沒有公網 IP 的主機接到外網

需求背景

A 城市與 B 城市之間透過 VPN 相連,B 城市才是服務真正所在。C 城市的存取必須走公網,因此 B 城市理應有公網出口,但實際上 B 城市並沒有分配到公網 IP。於是把方案定為:C 城市 → 公網 → A 城市 → VPN → B 城市,由 A 城市充當代理跳板。

三件事

一、為 A 城市主機映射一個公網位址與埠。二、完成域名解析。三、設定 nginx 反向代理。

主設定檔

[root@wall nginx]$ cat nginx.conf
#basic
user nginx;
worker_processes 1;
pid /var/run/nginx.pid;
worker_rlimit_nofile 202400;

events
{
    use epoll;
    worker_connections 202400;
}

http
{
    fastcgi_connect_timeout 300s;
    fastcgi_send_timeout 300s;
    fastcgi_read_timeout 300s;
    include mime.types;
    default_type application/octet-stream;
    fastcgi_intercept_errors on;
    charset utf-8;
    server_names_hash_bucket_size 128;
    client_header_buffer_size 4k;
    large_client_header_buffers 4 32k;
    client_max_body_size 999m;
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 60;
    tcp_nodelay on;
    client_body_buffer_size 512k;

    proxy_connect_timeout 5;
    proxy_read_timeout 28400;
    proxy_send_timeout 28400;
    proxy_buffer_size 16k;
    proxy_buffers 4 64k;
    proxy_busy_buffers_size 128k;
    proxy_temp_file_write_size 128k;

    gzip on;
    gzip_disable "MSIE [1-6]\.";
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 2;
    gzip_types text/plain application/x-javascript text/css application/xml;
    gzip_vary on;

    ###2012-12-19 change nginx logs
    log_format main '$http_x_forwarded_for - $remote_user [$time_local] "$http_host" "$request" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" $request_time $remote_addr';

    #加載vhost
    include /etc/nginx/conf.d/*.conf;
}

虛擬主機設定

[root@wall conf.d]$ cat wall.conf
upstream wall {
    server 192.168.1.2:80; (B城市服務器地址)
    #check interval=3000 rise=2 fall=5 timeout=30000;
}

server {
    listen 83;
    server_name wall*;

    location /
    {
        proxy_next_upstream http_502 http_504 error timeout invalid_header;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        #proxy_set_header X-Forwarded-Proto https;
        proxy_pass https://wall;
        expires off;
    }
}

幾個實務提醒:upstream 指向的是 VPN 內部的 B 城市位址,A 城市必須能通;三個 X-Forwarded 標頭務必帶上,否則後端看到的來源 IP 全是代理機,日誌與限流都會失真;proxy_read_timeout 拉得長,是為了應付跨城鏈路較慢的情況。若後端有需要回傳真實用戶 IP 的應用,記得確認它有讀取 X-Forwarded-For。

Copyright © Linux教程網 All Rights Reserved