
问题描述当使用Nginx部署Vue项目或其他前端SPA应用时直接访问首页可以正常显示但刷新非首页路由或直接访问子路由时会出现404错误。问题原因这是因为Vue作为单页应用(SPA)其路由是由前端JavaScript控制的。当你在浏览器中直接访问一个子路由如/about时浏览器会向服务器请求/about这个路径Nginx会尝试在服务器上查找/about这个文件或目录由于Vue是SPA实际上只有index.html一个入口文件所以Nginx找不到/about资源返回404解决方案方案一修改Nginx配置推荐场景一该域名仅部署了 Vue 项目在Nginx配置中添加try_files指令将所有请求重定向到index.htmlserver { 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项目核心配置 ## 使用场景SPA 单页前端路由 location /home/ { root /www/wwwroot/zhgl/web/; try_files $uri $uri/ /home/index.html; } ## 使用场景多页面静态 html 站点 location /help/ { root /www/wwwroot/zhgl/web/; index index.html; try_files $uri $uri.html $uri/ $uri/index.html 404; } 或 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模式constrouternewVueRouter({mode:history,routes:[...]})方案三使用hash模式不推荐如果你不想修改服务器配置可以将路由模式改为hash模式constrouternewVueRouter({mode:hash,routes:[...]})这样URL会变成类似http://example.com/#/about的形式刷新不会出现问题但URL不够美观。配置说明try_files $uri $uri/ /index.htmlNginx会依次尝试查找精确匹配的文件$uri匹配的目录$uri/如果都找不到则返回index.html由前端路由处理验证配置修改配置后执行以下命令验证并重载Nginxsudonginx-t# 测试配置是否正确sudonginx-sreload# 重载配置其他注意事项Base URL如果你的项目不是部署在根路径下需要设置Vue Router的base选项和Nginx的location匹配静态资源确保静态资源路径正确可能需要配置publicPath后端API如果有后端API需要配置Nginx代理通过以上配置你的Vue项目应该可以在Nginx上正常运行并且刷新页面也不会出现404错误了。