问题描述
当使用Nginx部署Vue项目(或其他前端SPA应用)时,直接访问首页可以正常显示,但刷新非首页路由或直接访问子路由时,会出现404错误。
问题原因
这是因为Vue作为单页应用(SPA),其路由是由前端JavaScript控制的。当你在浏览器中直接访问一个子路由(如/about)时:
- 浏览器会向服务器请求
/about这个路径 - Nginx会尝试在服务器上查找
/about这个文件或目录 - 由于Vue是SPA,实际上只有
index.html一个入口文件,所以Nginx找不到/about资源,返回404
解决方案
方案一:修改Nginx配置(推荐)
场景一:该域名仅部署了 Vue 项目
- 在Nginx配置中添加
try_files指令,将所有请求重定向到index.html:
server {
listen 80;
server_name yourdomain.com;
root /path/to/your/vue/dist;
location / {
try_files $uri $uri/ /index.html;
}
}
或者更完整的配置示例:
server {
listen 80;
server_name yourdomain.com;
root /path/to/your/vue/dist;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
# 静态资源缓存配置
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires max;
log_not_found off;
}
# 防止直接访问index.html
location = /index.html {
internal;
}
}
场景二:该域名同时有后端接口(如 PHP)+ Vue 项目
- 如果你的域名下还有后端接口(比如/api路径),需区分路径配置,避免冲突:
## 第一种:域名下只有一个Vue项目
server {
listen 80;
server_name your-domain.com;
# 后端项目根目录(如果有)
root /www/wwwroot/memberdemo;
index index.php index.html index.htm;
# 处理后端接口(比如PHP)
location /api/ {
index index.php index.html index.htm;
try_files $uri $uri/ /index.php?$query_string;
}
# 处理Vue项目(核心配置)
location / {
# 明确指向Vue打包目录的index.html
root /www/wwwroot/memberdemo/public/web;
try_files $uri $uri/ /index.html;
}
}
## 第二种:如果同一个域名下,为两个不同的 Vue 项目(比如 PC 端和移动端)配置 Nginx,同时保留后端 PHP 接口,核心问题是不能同时用两个 location / 配置,需要通过不同的 URL 路径前缀来区分这两个 Vue 项目。
server {
listen 80;
server_name your-domain.com;
# 后端项目根目录(如果有)
root /www/wwwroot/memberdemo;
index index.php index.html index.htm;
# 处理后端接口(比如PHP)
location /api/ {
index index.php index.html index.htm;
try_files $uri $uri/ /index.php?$query_string;
}
# 处理多个Vue项目(核心配置)
location /web/ {
root /www/wwwroot/memberdemo/public;
try_files $uri $uri/ /web/index.html;
}
location /mobile/ {
root /www/wwwroot/memberdemo/public;
try_files $uri $uri/ /mobile/index.html;
}
}
方案二:使用Vue Router的history模式
确保你的Vue Router配置为history模式:
const router = new VueRouter({
mode: 'history',
routes: [...]
})
方案三:使用hash模式(不推荐)
如果你不想修改服务器配置,可以将路由模式改为hash模式:
const router = new VueRouter({
mode: 'hash',
routes: [...]
})
这样URL会变成类似http://example.com/#/about的形式,刷新不会出现问题,但URL不够美观。
配置说明
try_files $uri $uri/ /index.html:Nginx会依次尝试查找:- 精确匹配的文件(
$uri) - 匹配的目录(
$uri/) - 如果都找不到,则返回
index.html,由前端路由处理
- 精确匹配的文件(
验证配置
修改配置后,执行以下命令验证并重载Nginx:
sudo nginx -t # 测试配置是否正确
sudo nginx -s reload # 重载配置
其他注意事项
- Base URL:如果你的项目不是部署在根路径下,需要设置Vue Router的base选项和Nginx的location匹配
- 静态资源:确保静态资源路径正确,可能需要配置publicPath
- 后端API:如果有后端API,需要配置Nginx代理
通过以上配置,你的Vue项目应该可以在Nginx上正常运行,并且刷新页面也不会出现404错误了。

8179

被折叠的 条评论
为什么被折叠?



