核心问题:vue‑router 使用 history 模式时,刷新页面 404,需要 nginx 把所有请求重定向到
index.html
最简可用配置
server {
listen 80;
server_name shturl.cc/aCWY;
# 打包后dist目录路径
root /data/www/vue-dist;
index index.html;
location / {
# 先找文件、再找文件夹,都不存在返回 index.html
try_files $uri $uri/ /index.html;
}
}
try_files 参数解释
try_files $uri $uri/ /index.html;
$uri:尝试访问请求的文件,例如/about→ 找about文件$uri/:尝试当做目录访问,查找目录下 index 文件/index.html:前面都找不到,返回首页,交给 vue‑router 接管路由
带二级子目录(publicPath)场景
如果你 vue 打包时设置了 publicPath: '/app/',访问地址 shturl.cc/aCWY/app/
server {
listen 80;
server_name shturl.cc/aCWY;
root /data/www;
location /app/ {
try_files $uri $uri/ /app/index.html;
}
}
生产完整推荐配置(含缓存、gzip)
server {
listen 80;
server_name vue.example.com;
root /opt/vue/dist;
index index.html;
# 静态资源长缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 365d;
add_header Cache-Control "public, immutable";
}
location / {
try_files $uri $uri/ /index.html;
}
# 开启gzip
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}
常见坑 & 报错排查
- 空白页 / 无限重定向
- 检查
root路径是否正确,目录下真实存在index.html - 不要写成
alias+ try‑files 组合(子路径很容易出错)
- 检查
- 接口 404 api 请求不能被前端路由接管,后端接口要单独反向代理:
location /api/ {
proxy_pass http://127.0.0.1:8080/;
}
- 修改配置后重载 nginx
# 检查语法
nginx -t
# 重载配置
nginx -s reload
正文完
可以使用微信扫码关注公众号(ID:xzluomor)