Nginx 部署 Vue 项目以及 Vue 项目刷新出现 404 的问题(完整步骤)(亲测有效)

Nginx 部署 Vue 项目以及 Vue 项目刷新出现 404 的问题(完整步骤)(亲测有效)

1.流程步骤(本教程下载的是1.20.2版本,放在D盘)

1-1. 首先去官方下载 nginx ,然后在当前目录下创建html文件夹,html下再创建h5和web文件夹分别代表H5项目和管理后台项目
1-2. 分别将不同的项目代码放到不同的项目里面(注意: vue-cli 项目需将打包后的文件放到对应的文件夹)

2.nginx.conf 配置


server {
    
    
	listen 80; //默认
	location / {
    
    
		root D:/nginx-1.20.2/html/website;
		index index.html;             
           try_files $uri $uri/ /website/index.html last;
		   error_page 404 /website/index.html;
       }
}

server {
    
    
        listen       1080; //自定义
        server_name  192.168.88.68; 

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        
		# 允许跨域GET,POST,DELETE HTTP方法发起跨域请求
	    #add_header 'Access-Control-Allow-Origin' *;
	    #add_header 'Access-Control-Allow-Credentials' 'true';
	    #add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accep,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Requested-With';
	    #add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE';
		#if ($request_method = OPTIONS) {
    
    
		#return 200;
		#}

		# 官网 nginx 部署
        location ^~/website{
    
    
			index index.html;             
            try_files $uri $uri/ /website/index.html last;
			error_page 404 /website/index.html;
        }

		#帮助信息,图片文件资源,后台api
		location ~ /(helpInfo|image)/ {
    
    
			proxy_redirect off;
			proxy_set_header  Host $host;
            proxy_set_header   X-real-ip $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_pass http://localhost:8009;
        }

		# vue-web管理后台(测试环境)
		location ^~/vue-web-test {
    
    
			index index.html;             
            try_files $uri $uri/ /vue-web-test/index.html last;
			error_page 404 /vue-web-test/index.html;
        }
        
		# vue-web管理后台(生产环境)
		location ^~/vue-web-prod {
    
    
			index index.html;             
            try_files $uri $uri/ /vue-web-prod/index.html last;
			error_page 404 /vue-web-prod/index.html;
        }
}
vue 项目访问链接:http://192.168.88.68:1080/vue-web-test/index

3.遇到的问题

vue-web部署上去后首次访问正常,但刷新后却出现404
问题解决:检查配置是否正确,包括字母是否错误,如下举例所示
# vue-web管理后台(测试环境)
location ^~/vue-web-test {
    
    
	index index.html;             
    try_files $uri $uri/ /vue-Web-test/index.html last;
	error_page 404 /vue-web-test/index.html;
}

首次进入界面可以正常,但一刷新界面就404
404
问题所在:try_files $uri $uri/ /vue-Web-test/index.html last;(中的Web写成了大写),三个地方的vue-web-test都得一致,否则就会出现404情况。

注意:需检查三个地方的命名是否一致,是否严格按照驼峰命名

猜你喜欢

转载自blog.csdn.net/mrliucx/article/details/129143050