常见3种方法来实现在一台服务器上使用nginx部署多个前端项目的方法。
- 基于域名配置
- 基于端口配置
- 基于location配置
基于域名配置
基于域名配置,前提是先配置好了域名解析。比如说你自己买了一个域名:www.test.com。 然后你在后台配置了2个它的二级域名: a.test.com、 b.test.com。
配置文件如下: 配置 a.test.com 的配置文件:
vim /usr/nginx/modules/a.conf
server {
listen 80;
server_name a.test.com;
location / {
root /data/web-a/dist;
index index.html;
}
}
配置 b.test.com 的配置文件
vim /usr/nginx/modules/b.conf
server {
listen 80;
server_name b.test.com;
location / {
root /data/web-b/dist;
index index.html;
}
}
这种方式的好处是,主机只要开放80端口即可。然后访问的话直接访问二级域名就可以访问。
基于端口配置
配置文件如下:配置 a.test.com 的配置文件:
vim /usr/nginx/modules/a.conf
server {
listen 8000;
location / {
root /data/web-a/dist;
index index.html;
}
}
# nginx 80端口配置 (监听a二级域名)
server {
listen 80;
server_name a.test.com;
location / {
proxy_pass http://localhost:8000; #转发
}
}
配置 b.test.com 的配置文件:
vim /usr/nginx/modules/b.conf
server {
listen 8001;
location / {
root /data/web-b/dist;
index index.html;
}
}
# nginx 80端口配置 (监听b二级域名)
server {
listen 80;
server_name b.test.com;
location / {
proxy_pass http://localhost:8001; #转发
}
}
可以看到,这种方式一共启动了4个server,而且配置远不如第一种简单,所以不推荐。
基于location配置
配置文件如下: 配置 a.test.com 的配置文件:
vim /usr/nginx/modules/ab.conf
server {
listen 80;
location / {
root /data/web-a/dist;
index index.html;
}
location /web-b {
alias /data/web-b/dist;
index index.html;
}
}
注意: 这种方式配置的话,location / 目录是root,其他的要使用alias。
可以看到,这种方式的好处就是我们只有一个server,而且我们也不需要配置二级域名。并且前端项目里要配置二级目录
react 配置请参考: blog.csdn.net/mollerlala/…
vue 配置请参考:blog.csdn.net/weixin_3386…