1. publicPath配置(vite中是base属性):
publicPath配置build打包的资源存放公共路径,当我们打包的时候webpack会在静态文件路径前面添加publicPath的值,一般和router里base属性结合使用(加载时会此publicPath目录中寻找资源)。当我们把资源放到CDN上的时候,把publicPath的值设为cdn地址
比如配置了publicPath: /project/hx.con
在index.html入口文件中打包后的chunk.js、chunk.css等资源都会加前缀路径(/project/hx.con/chunk.js)
然后我们需要将打包后资源放到【nginx root指定的根目录】/project/hx.con下:mv ./dist /lbsmart.public/project/hx.con
2.nginx root/alias location定位资源
root、alias都是用来指定url根路径(/)代表的资源目录的。
使用root:当你想为整个服务器或者特定位置提供一个统一的根目录时,使用root是最简单直接的方法。
使用alias:当你需要对服务器上的特定资源进行映射,而这部分资源又不在当前的根目录中时,alias是不可或缺的(alias会把location后面配置的路径丢弃掉)
比如如下nginx配置:
index index.html; # 网站初始页(即直接localhost:端口 访问的页面)
root /lbsmart.public; #根目录
location / { index index.html; }
访问http://localhost/project/hx.con时:
即从/lbsmart.public/project/hx.con/index.html 这个路径加载index.html资源文件并返回。
额外: 重写 & 重定向
利用URL重写,我们可以很方便地实现长短地址的转换,但是用重定向就不合适了。
rewrite ^grab /public/files/download/download.php ( rewrite {规则} {定向路径} {重写类型})
若访问http://mysite/grab?file=my.zip
则会执行该页面:
http://mysite/public/files/download/download.php?file=my.zip
若是重定向规则:(浏览器端重新发请求)
若访问http://mysite/grab?file=my.zip
则会执行该页面:
http://mysite/public/files/download/download.php
3.router配置 base(保证路由能识别publicPath前缀)
对于history模式,假设项目的publicPath为/project/hx.con。
3-1.由于router中路由的path一般是/about这样。 为了让router可以识别到localhost/project/hx.con/about,需要配置router的参数: base: /project/hx.con
3-2.访问http://localhost/project/hx.con/about的时候,服务器会去找/project/hx.con指向的打包资源目录下的about子目录或文件,很显然因为是单页面应用,并不会存在about这个目录或者文件,就会导致404错误:
我们要配置nginx让这种情况下,服务器能够返回单页应用的index.html,然后剩下的路由解析的事情就交给前端vue-router来完成即可。
root /lbsmart.public;
location / {
try_files $uri $uri/ @router;
index index.html;
}
location @router {
rewrite ^.*$ /index.html last;
}
这句配置的意思就是,拿到一个地址,先根据地址尝试找对应文件,找不到再试探地址对应的文件夹,再找不到就返回rewrite /index.html的结果(即/lbsmart.public/project/hx.con/index.html文件)。再次打开刚才的about地址,刷新页面也不会404啦.
4.axios配置baseURL
为了避免后端接口端口和前端不同导致cors跨域,一般会设置一个接口的公共前缀baseURL,这样axios发出的所有接口都会增加这个前缀url。
比如: baseURL: /prod-api
然后nginx中可以配置location转发以/prod-api开头的url给后端服务处理。
location /prod-api/ { #后端接口转发
proxy_pass http://10.100.2.74:9151; #后端接口地址
proxy_cookie_path / /prod-api;
rewrite ^/prod-api/(.*) /$1 break;
client_max_body_size 500m;
}
PS:完整nginx.conf参数配置见`ubuntu22部署 vue 和 springboot项目_ubuntu nodejs+vue + element-plus + springboot环境搭建-CSDN博客`部分: