-
Preface
-
Configure nginx multiple services to share port 80
-
Solution 1: Multiple different port services share port 80
-
Solution 2: Multiple services share port 80
-
Preface
Since a company server has multiple services at the same time, these services hope to listen to the 80/443 port and access it directly through the domain name through domain name resolution, such as demo.test.com and product.test.com. At this time, we can use the proxy forwarding function of nginx to help us realize the need to share the 80/443 port.
Note: Since the HTTP protocol listens to port 80 by default and the HTTPS protocol listens to port 443 by default, when using a browser to access services on port 80/443, you can ignore the ":80/:443" port after the domain name and directly configure the port to listen to port 80. , access is more convenient.
Configure nginx multiple services to share port 80
First find the nginx configuration file
通过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!强制退出并保存)
The following is an example of two services accessed using domain names and sharing port 80.
方案一:
Multiple different port services share port 80
1) Configure nginx.conf file
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) Restart the nginx service after the configuration is completed
#systemctl restart nginx
3) If it is a local LAN, you need to configure the network to map the corresponding ports. In my case, the three ports 80, 8001, and 8002 are mapped to the public IP, and the corresponding domain names are resolved. After completion, you can access it normally;
- Solution 2: Multiple services share port 80
1) Configure nginx.conf file
// 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) Refer to plan 1. After the configuration is completed, save it, restart the nginx service, and access the test.