这里介绍的是所有请求不管是前端还是后端都是在一个域名下。
但是 但是 但是,如果你能控制域名的映射强烈建议你使用多个二级域名来实现。
1.打开 Nginx 的配置文件 nginx.conf
,该文件通常位于 /etc/nginx/
或者 /usr/local/nginx/conf/
中。
2.修改nginx配置如下:
server {
listen 80;
server_name laker.com www.laker.com; // 设置为自己的域名或 IP 地址
# 官网 http://laker.com
location / {
# root类型的注意后面dist不带 "/"
root /laker/index/dist; #dist文件的位置(根据自己dist包放置的位置决定)
try_files $uri $uri/ /index.html; #重写 URL,使得所有页面都能正确访问到 index.html
index index.html index.htm;
}
# 项目一 http://laker.com/mall访问
location /mall {
# 项目路径是alias不是root,dist后面有个“/”
alias /laker/mall/dist/;
# 这里重写url,最后的/mall/index.html 跟location呼应
try_files $uri $uri/ /mall/index.html;
index index.html index.htm;
}
# 项目二 http://laker.com/mall-admin访问
location /mall-admin {
alias /laker/mall-admin/dist/;
index index.html index.htm;
try_files $uri $uri/ /mall-admin/index.html; // 重写 URL,使得所有页面都能正确访问到 index.html
}
# 反向代理后端接口
# 有跨域示例
# http://laker.com/mall-api/getUserInfo到http://127.0.0.1:8082/getUserInfo
# 剔除了路径中的"mall-api"
location /mall-api/ {
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Headers $http_access_control_request_headers;
add_header Access-Control-Allow-Methods $http_access_control_request_method;
add_header Access-Control-Allow-Credentials 'true';
return 204;
}
if ($request_method != 'OPTIONS') {
# 动态$http_origin 或者指定一些域名
add_header Access-Control-Allow-Origin 'http://localhost:8080' always;
add_header Access-Control-Allow-Credentials 'true';
}
proxy_pass http://127.0.0.1:8082/;
proxy_connect_timeout 30; #超时时间 单位秒
proxy_send_timeout 60;
proxy_read_timeout 60;
}
# 无跨域示例
location /mall-admin-api/ {
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-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:8083/;
}
}
修改完成后,保存并关闭配置文件。
3.重新加载 Nginx 配置,命令如下:
sudo nginx -s reload
4.在浏览器测试
- http://laker.com
- http://laker.com/mall
- http://laker.com/mall-admin