

nginx发布vue,nginx异常处理404处理,结合nginx优化路由404。vue项目发布在服务器中

nginx发布vue
这里用vue3-admin-template来举例,其实都是一样的。
先打包
使用的打包命令类似npm run build:prod
,反正根据实际情况打包出来即可。打包出来之后基本就是一套静态页面的内容了,把它放到nginx的html文件夹里边。
里边的内容如下:
然后配置nginx:
server {
# 监听的端口号
listen 9200;
# 服务名称 生产环境要修改成 公网ip 如 49.109.136.127
server_name localhost;
# 配置默认的主页显示 比如 49.109.136.127:9200 显示的 index 页面
location / {
# 根目录就是刚刚打包出来存放的位置
root html/vue3-admin-template;
index index.html;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
配置好了,使用命令start nginx
启用nginx,进行访问即可
注意在.config.js配置中base的配置会影响打包后静态资源的路径
如果配置错了,会影响发布到nginx后访问静态资源的问题,会出现404。
比如我们刚刚上传nginx那样的配置方式,在base里边就不能配置成base:'vue3-admin-template'
,那样静态资源就会相对vue3-admin-template目录去找是找不到的。反正就是静态资源引用的路径问题,知道原理了具体情况具体分析就行。
还有一种常用的发布方式,就是打包的时候base加上vue3-admin-template。然后nginx的配置写成下图这种。就是nginx配置的不接文件夹的方式,直接还是在html页面
访问的时候,就要这样访问了http://localhost:9200/vue3-admin-template 。就是要在地址栏后面加上文件夹的名称,其实这样做就相当于整个html文件夹里边都是一个大的项目,里边的子文件夹都是属于这个大项目下的一个模块或者说是子项目,有时候我们就是需要这种需求,这样就可以在开发的时候分成完全独立的项目开发,发布的时候又能合并到一起形成一个统一的大项目,nginx的配置很灵活的,根据实际情况使用即可。
下面这种配置其他地方看到的贴一下,需要用的时候也可以参考一下。
http {
server {
# 监听的端口号
listen 9200;
# 服务名称 生产环境要修改成 公网ip 如 47.105.134.120
server_name localhost;
# 配置根目录的地址是以 nginx 下的 html 文件夹为根目录来查找的
root html;
# 配置默认的主页显示 比如 47.105.134.120:8080 显示的 index 页面
location / {
try_files $uri $uri/ /index.html;
}
# 配置我们的 admin 的前台服务 比如 47.105.134.120:8080/admin/index.html
location ^~ /admin {
# 处理 Vue 单页面应用 路由模式为 history 模式刷新页面 404 的问题
try_files $uri $uri/ /admin/index.html;
}
# 如果你想配置多个项目的话,可以复制上面的,修改一下就可以同时部署多个前端项目了
# 比如
# location ^~ /blog {
# 处理 Vue 单页面应用 路由模式为 history 模式刷新页面 404 的问题
# try_files $uri $uri/ /blog/index.html;
# }
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
include servers/*;
}
nginx处理vue项目404异常,结合nginx优化路由404
解决思路:
nginx检查404,然后跳转到首页并且把404的页面地址当做参数传递进去,然后在首页获取到那个发生404的地址,在进行跳转。
nginx的配置方法
server {
listen 8001;
server_name localhost;
root E:\CloundInv\LandWecaht;
location / {
try_files $uri $uri/ @router;
}
location @router {
rewrite ^(.*)$ http://$http_host?redirecturl=$uri last;
}
}
try_files的意思就是监听异常的出现,比如404,500应该也监听得,然后执行了@router,在下面就跳转到了,首页去,然后了一个$uri的参数,就是发现404的页面,然后在首页获取到那个发生404的地址,在进行跳转。
vue中首页的处理
created() {
let rurl = this.$route;
if (rurl.fullPath.includes("redirecturl")) {
let _url = rurl.fullPath.replace("&", "?").replace("/?redirecturl=", "");
console.log(`redirect:${rurl.fullPath}->${_url}`);
this.$router.push(_url);
}
this.streets = streetdatas;
this.street = streetdatas[0].streetname;
this.activename = streetdatas[0].streetname;
let an = this.$route.query.an;
if (an) {
this.streetgroup_vbs = true;
this.activename = an;
this.street = an;
}
},
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)