问题描述
Vue 2 项目打包时设置了 publicPath: '/web/'
,并通过 Nginx 配置访问 http://ip/web
时可以正常加载首页,但刷新页面时出现 404 错误
原nginx的配置
location /web {
alias /www/dist; # 静态文件地址
try_files $uri $uri/ /index.html;
index index.html index.htm;
}
vue的vue.config.js
module.exports = {
// 例如 https://www.xxx.com。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://www.xxx.com/web,则设置 /web/。
publicPath: '/web/',
#省略
}
问题原因
-
当访问
http://ip/web
时,Nginx 会正确返回/www/dist/index.html
。 -
但当刷新页面或直接访问子路由(如
http://ip/web/about
)时,Nginx 会尝试查找/www/dist/about
文件,但该文件不存在,因此返回 404 错误。
解决方法
需要在 try_files
中正确处理子路径 /web
,将所有请求重定向到 /web/index.html
。
将 try_files
的路径改为 /web/index.html
,确保所有请求都返回 index.html
,由 Vue 路由处理。
nginx配置
location /web {
alias /www/dist; # 静态文件地址
try_files $uri $uri/ /web/index.html; # 处理子路径
index index.html index.htm;
}
配置说明
-
alias /www/dist;
:-
将
/web
路径映射到/www/dist
目录。
-
-
try_files $uri $uri/ /web/index.html;
:-
$uri
:尝试匹配请求的文件。 -
$uri/
:尝试匹配请求的目录。 -
/web/index.html
:如果以上都找不到,则返回/web/index.html
,由 Vue 路由处理。
-
-
index index.html index.htm;
:-
默认加载
index.html
或index.htm
。
-
验证步骤
-
修改 Nginx 配置文件后,重新加载 Nginx:
sudo nginx -s reload
-
访问
http://ip/web
,确保首页可以正常加载。 -
刷新页面或直接访问子路由(如
http://ip/web/about
),确保不再出现 404 错误。
注意事项
-
alias
和root
的区别:-
alias
会完全替换location
的路径。 -
root
会将location
的路径附加到指定的目录后。 -
例如:
location /web { alias /www/dist; # /web -> /www/dist }
等同于:
location /web { root /www; # /web -> /www/web }
-
-
publicPath
配置:-
确保 Vue 项目的
publicPath
配置为/web/
,与 Nginx 的location /web
一致。
-
总结
-
修改 Nginx 配置,将
try_files
的路径改为/web/index.html
。 -
确保 Vue 项目的
publicPath
配置为/web/
。 -
重新加载 Nginx 并验证页面刷新是否正常。