Nginx根据域名转发到不同的服务

0.背景

外网只放开了3955端口,现在根据不同的域名进行转发,例如:

aa.test.com:3955 -> http://10.7.0.1:3009
bb.test.com:3955 -> http://10.7.0.2:1337

1.Nginx配置

1.1 配置server

1.1.1 aa.test.com

    server{
    listen 3955;
    server_name aa.test.com aa.test.com;
    proxy_intercept_errors on;
    error_page 500 502 503 504  /50x.html;
    error_page 404   /404.html;
	
    location / {
    	proxy_pass http://10.7.0.1:3009;
    }
    location ~ \.(gif|jpg|png|js|css|mp4|ico)$ {
    	proxy_pass http://10.7.0.1:3009;
    }
    location = /404.html {
    	root html;
    }
  }

1.1.2 bb.test.com

    server{
    listen 3955;
    server_name bb.test.com bb.test.com;
    proxy_intercept_errors on;
    error_page 500 502 503 504  /50x.html;
    error_page 404   /404.html;
	
    location / {
    	proxy_pass http://10.7.0.2:1337;
    }
    location ~ \.(gif|jpg|png|js|css|mp4|ico)$ {
    	proxy_pass http://10.7.0.2:1337;
    }
    location = /404.html {
    	root html;
    }
  }

1.2 重载Nginx

./nginx -s reload

# 告警3955端口有冲突的server name,证明配置成功。
nginx: [warn] conflicting server name "aa.test.com" on 0.0.0.0:3955, ignored
nginx: [warn] conflicting server name "bb.test.com" on 0.0.0.0:3955, ignored

1.3 修改host文件测试

# Nginx
10.7.12.14 aa.test.com
10.7.12.14 bb.test.com

经测试,此时如果不通过域名,直接通过nginx的ip访问,会访问到先配置的server上。
可以从上面的告警日志中看到顺序,即10.7.12.14:3955会访问到aa.test.com的server。

posted @ 2023-01-28 10:01  羊37  阅读(70)  评论(0编辑  收藏  举报