前言

最近使用Nginx部署Vue项目时,发现页面偶尔会出现404的情况,而且是概率事件,不是百分百,网上搜寻了一下解决方法,原来是由于Vue单页面开发特性导致的,这里记录一下解决方法。

开始

只需要在Nginx配置中添加以下内容即可:

1
2
3
4
5
6
7
location / {
try_files $uri $uri/ @router;
index index.html index.htm;
}
location @router {
rewrite ^.*$ /index.html last;
}

完整配置案例(1Panel的Nginx配置案例):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
server {
listen 80 ;
listen 443 ssl http2 ;
server_name xxx.xxx.xx; # 你的域名
index index.php index.html index.htm default.php default.htm default.html;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $http_connection;
access_log /www/sites/xxx.xxx.xx/log/access.log main;
error_log /www/sites/xxx.xx.xx/log/error.log;
location ^~ /.well-known/acme-challenge {
allow all;
root /usr/share/nginx/html;
}
root /www/sites/xxx.xxx.xx/index/dist;
# 加到这里
location / {
try_files $uri $uri/ @router;
index index.html index.htm;
}
location @router {
rewrite ^.*$ /index.html last;
}
error_page 404 /404.html;
if ($scheme = http) {
return 301 https://$host$request_uri;
}
# 这里省略ssl的配置
}

更改配置重载即可

参考文档

解决 nginx部署vue刷新、访问路由页面404