vue项目部署nginx后 找不到子路径页面的解决方法
使用try_files属性
location / {
root /app/web;
try_files $uri $uri/ @router; #检测文件是否存在不存在则重定向到首页目录 防止404
index index.html index.htm;
#proxy_set_header Host $host;
#nginx非80端口处理 加上 :$server_port
client_max_body_size 10m;
client_body_buffer_size 128k;
}
location @router {
rewrite ^.*$ /index.html last;
}
在项目的子路由下刷新页面出现了404,这是因为刷新页面时访问的资源在服务端找不到,因为vue-router设置的路径不是真实存在的路径。
当用户请求 http://localhost/example 时,这里的 $uri 就是 /example。
try_files 会到硬盘里尝试找这个文件。如果存在名为 /$root/example(其中 $root 是项目代码安装目录)的文件,就直接把这个文件的内容发送给用户。