一、Nginx实现方法
- 基于域名配置
- 基于端口配置
- 基于location配置
二、基于域名配置
基于域名配置,前提是先配置好了域名解析。比如说你自己买了一个域名:www.fly.com。 然后你在后台配置了2个它的二级域名: a.fly.com、 b.fly.com。
配置文件如下:
配置 a.fly.com 的配置文件:
vim /usr/nginx/modules/a.conf
1 2 3 4 5 6 7 8 9 |
|
配置 b.fly.com 的配置文件:
vim /usr/nginx/modules/b.conf
1 2 3 4 5 6 7 8 9 |
|
这种方式的好处是,主机只要开放80端口即可。然后访问的话直接访问二级域名就可以访问。
三、基于端口配置
配置文件如下:
配置 a.fly.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.fly.com;
location / {
proxy_pass http://localhost:8000; #转发
}}
配置 b.fly.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.fly.com;
location / {
proxy_pass http://localhost:8001; #转发
}
}
可以看到,这种方式一共启动了4个server,而且配置远不如第一种简单,所以不推荐。
四、基于location配置
配置文件如下:
配置 a.fly.com 的配置文件:
vim /usr/nginx/modules/ab.conf
server {
#这里默认监听80端口,可根据项目需要自行设置需要监听的端口号
listen 80;
server_name 此处填写项目发布的域名或者ip地址;
location / {
root 此处填写前端项目文件路径(默认访问的前端项目一的路径);
index index.html index.htm;
}
#这里因为每个server只能有一个root 所以在根目录默认有root之后,可以通过alias来配置其他文件路径
#ex: http://www.xxx.com:xxx/unst/#/xxx,将/unst这个前置在页面跳转时加入url的#号之前即可
location /unst {
alias 此处填写前端项目文件路径(前端项目二的路径);
index index.html index.htm;
}
#前端项目一对应的后端服务一的跳转配置
location /st/ {
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8089;
}
#前端项目二对应的后端服务二的跳转配置
location /un/ {
proxy_pass http://127.0.0.1:8091;
}
}
注意: 这种方式配置的话,location / 目录是root,其他的要使用alias。
可以看到,这种方式的好处就是我们只有一个server,而且我们也不需要配置二级域名。并且前端项目里要配置二级目录