vue3打包成dist文件部署到nginx,页面刷新显示404的解决办法

说明

1本操作是将vue3项目通过yarn  run  build-only打包成dist文件,但是dist文件只有一个index.html,其余都是js和css
2将dist文件部署到nginx环境中,运行后台,可以正常访问,但是刷新页面显示404,这是因为打包后的文件根本找不到原来的vue页面,需要重定向接口页面

1如果是通过vue打包生成的dist文件,里面只有一个index.html,这个时候配置一定不要配置太多的拦截,否则会报404,可以使用以下方式配置就够了
server {
        listen 后台端口;
        server_name localhost;
       location ^~ /local_api/ {
             proxy_pass   http://后台ip:后台端口;
             proxy_set_header   Host             $host:$server_port;
             proxy_set_header   X-Real-IP        $remote_addr;
             proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
             add_header From www.weixin4j.org;
             proxy_set_header Cookie $http_cookie;
        }
        location / {
           charset utf-8;
           root   html/deploy/vue3/dist;
           index  index.html;
           try_files $uri $uri/ /index.html;
        }
    }    
或者
 server {
        listen 后台端口;
        server_name localhost;
       location ^~ /local_api/ {
             proxy_pass   http://后台ip:后台端口;
             proxy_set_header   Host             $host:$server_port;
             proxy_set_header   X-Real-IP        $remote_addr;
             proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
             add_header From www.weixin4j.org;
             proxy_set_header Cookie $http_cookie;
        }
        location / {
           charset utf-8;
           root   html/deploy/vue3/dist;
           index  index.html;
        if (!-e $request_filename){
                rewrite ^(.*)$ /index.html?s=$1 last;
                break;
            }
        }
    }

其中关键的是


 try_files $uri $uri/ /index.html;
和
 if (!-e $request_filename){
                rewrite ^(.*)$ /index.html?s=$1 last;
                break;
            }

配置好了之后覆盖原来的html页面,即可解决404问题

如果出现了白板,说明vite.config.ts里面可能出现问题,修改好即可

更多推荐