VUE-cli3打包上线到服务器子目录与NGINX服务器规则配置

根目录下vue.config.js配置如下
nginx1.jpg
module.exports = {

	publicPath:  process.env.NODE_ENV === 'production'
    ? '/h5-case/'
    : '/',
   
	devServer : {
		proxy : {
			'/apis' : {
				target : 'https://www.yihudong.cn',
				ws : true,
				changeOrigin : true,
				pathRewrite : {
					'^/apis' : '/'  //这里理解成用 /apis/ 代替target里面的地址                    
				}
			}
		}
	},
	
}


axios的get请求地址这样写

axios.get('/apis/list.php')

打包build编译并压缩上传到服务器主机的 h5-case子目录,主机nginx添加静态规则或者修改主机.conf配置文件添加以下内容

location ^~ /apis/ 
{ 
proxy_set_header Host www.yihudong.cn; 
proxy_pass https://www.yihudong.cn/; 
}
#如果路由router的mode: 'history' 设置为history,就要下面的规则
location / {
  try_files $uri $uri/ /h5-case/index.html;
}

查看demo


注释:
location ^~ /apis/ 
{ 
proxy_set_header Host www.yihudong.cn; 
proxy_pass https://www.yihudong.cn/; 
}
nginx规则按上面的配置,如果请求的url是 https://www.a.com/apis/list.php 就会被代理成 https://www.yihudong.cn/list.php

location ^~ /apis/ 
{ 
proxy_set_header Host www.yihudong.cn; 
proxy_pass https://www.yihudong.cn; 
}
而如果规则是上面的配置,就会被代理到 https://www.yihudong.cn/apis/list.php

注意:这是因为proxy_pass如果是用 ^~ 来匹配路径 的时候,如果url最后加上了 / ,相当于绝对根路径,nginx就不会把location里面到的路径代理到。如果没有 / ,则会把匹配的路径部分也代理到。


location / {
  try_files $uri $uri/ /h5-case/index.html;
}
我不喜欢URL中有#号,所以 router.js 中需把 mode 改成 history。这时候就要配置nginx规则了。如果是根目录上面 就可以直接 写成 index.html , 如果是子目录,index.html前面就要写上子目录名。这样在子页面的时候会访问到index.html文件。





暧昧贴