使用nginx根据不同域名转发到不同端口

2,522 阅读1分钟
原文链接: zhuanlan.zhihu.com

假如在同一台服务器上部署了2个server,分别对应8080,,8081端口,并用2个不同的域名分别对应这两个端口,我们可以使用nginx的转发动态请求到不同端口的应用上

1、需要配置/etc/nginx/conf.d/default.conf

www.a.net 需要请求到8080端口的应用
server {
listen 80;
server_name www.a.net;
location / {
proxy_pass http://127.0.0.1:8080;
index index.html index.htm;
}
}

www.a.cn 需要请求到8081端口的应用
server {
listen 80;
server_name www.a.cn;
location / {
proxy_pass http://127.0.0.1:8081;
index index.html index.htm;
}
}

2、检查配置,并重新加载配置

# 检查配置文件语法是否正确
nginx -t -c /etc/nginx/nginx.conf
#重新加载配置
nginx -s reload -c /etc/nginx/nginx.conf

3、将www.a.netwww.a.cn域名都配置到当前这台服务器的对外ip上,这样我们就可以通过访问不同的地址来实现不同端口的访问了

ok,done!