Nginx如何配置多个服务域名解析共用80端口详解

前言

由于公司一台服务器同时有多个服务,这些服务通过域名解析都希望监听80/443端口直接通过域名访问,比如有demo.test.com和product.test.com。这时候我们可以使用nginx的代理转发功能帮我们实现共用80/443端口的需求。

备注:由于HTTP协议默认监听80端口,HTTPS协议默认监听443端口,所以使用浏览器访问80/443端口的服务时,可以忽略域名后的“ :80/:443” 端口,直接配置监听到80端口,访问比较方便。

配置nginx多服务共用80端口

首先找到nginx配置文件    

通过apt-get install nginx命令安装的nginx默认配置文件存放在:/etc/nginx目录下
 
切换到/etc/nginx目录
 
#cd /etc/nginx #切换到nginx目录
 
# ls #查看nginx目录下文件
conf.d fastcgi_params koi-win modules-available nginx.conf scgi_params sites-enabled uwsgi_params fastcgi.conf koi-utf mime.types modules-enabled proxy_params sites-available snippets win-utf
 
#vim nginx.conf #打开nginx配置文件(输入shift+i插入内容,esc退出编辑,点击shift+:输入q退出当前页,q!强制退出,不保存编辑的内容;输入wq!强制退出并保存)

以下以两个服务使用域名访问,共用80端口为例

方案一:多个不同端口服务共用80端口

1)配置nginx.conf文件

1.先配置两个端口服务:
// nginx.conf
#demo
server {
 listen 8001;
 server_name localhost;
 try_files $uri $uri/ /index.html;
 root /home/www/demo;
}
#product
server {
 listen 8002;
 server_name localhost;
 try_files $uri $uri/ /index.html;
 root /home/www/product;
}
 
2.配置代理:
// nginx.conf
#demo转发
server {
 listen 80;
 server_name demo.test.com;
 location / {
 proxy_pass http://localhost:8001;
 }
}
#product转发
server {
 listen 80;
 server_name product.test.com;
 location / {
 proxy_pass http://localhost:8002;
 }
}

2)配置完成后重启nginx服务

#systemctl restart nginx

3)  如果是本地局域网需要配置网络将对应的端口,我这边是80,8001,8002三个端口映射到公网IP,并解析对应的域名,完成后就可以正常访问了;

方案二:多个服务共用80端口

1)配置nginx.conf文件

// nginx.conf
# nginx 80端口配置 (监听demo二级域名)
server {
 listen 80;
 server_name demo.test.com;
 location / {
 root /home/www/demo;
 index index.html index.htm;
 }
}
 
# nginx 80端口配置 (监听product二级域名)
server {
 listen 80;
 server_name product.test.com;
 location / {
 root /home/www/product;
 index index.html index.htm;
 }
}

2)参考方案一,配置完成后保存,重启nginx服务,访问测试。

总结

作者:空灵之海原文地址:https://blog.csdn.net/weixin_44569100/article/details/126179849

%s 个评论

要回复文章请先登录注册