nginx部署vue项目及nginx配置

nginx部署vue项目,vue.conf.js配置文件默认配置publicPath为根路径 publicPath:‘/’,只需要打包好dist包,部署nginx即可,根据前端配置好的axios请求前缀baseUrl='prod-api',配置拦截,跳转代理的后台接口即可。

   location / {
            root   /home/projects/web_front; 
            #当项目的vue-router使用history模式时,刷新界面会空白,或使用有参数的url时候会找不到地址,
            #例如:user/getByid/1 ,使用hash模式无此问题
            try_files $uri $uri/ /index.html;  
            index  index.html index.htm;
        }

当某些应用部署在内部网络,通往外网只放行了一个端口时,nginx需要配置统一端口的的多应用服务器(一个server内配置多个应用的时候例如电脑端访问http://x.x.x.x:8080,访问电脑端,http://x.x.x.x:8080/app时访问H5端),需要在vue.conf.js配置文件配置publicPath,例如 publicPath:‘/app’,当使用 publicPath:‘/app’时,需要配置配置nginx的location选项,将location的root配置项目改为alias

 location ^~app {
            alias   /home/projects/h5_front;
            #当项目的vue-router使用history模式时,刷新界面会空白,或使用有参数的url时候会找不到地址,
            #例如:user/getByid/1 ,使用hash模式无此问题
            try_files $uri $uri/ /index.html;  
            index  index.html index.htm;
        }

因为 nginx的location获取到匹配路径(/app)之后,root配置会使用ip+端口的方式请求nginx获取服务器的静态资源,(例如:http://x.x.x.x:8080/aaa.img),而使用alias配置时,会使用ip+端口+匹配的路径访问服务器静态资源,(例如:http://x.x.x.x:8080/app/aaa.img),此时可以正常访问服务器资源。不然会出现报错,找不到服务器静态资源。

nginx配置

server {
        listen       8080;
        server_name  localhost;
		#例如:/ 根路径为电脑端
        location / {
            root   /home/projects/web_front; 
            #当项目的vue-router使用history模式时,刷新界面会空白,或使用有参数的url时候会找不到地址,
            #例如:user/getByid/1 ,使用hash模式无此问题
            try_files $uri $uri/ /index.html;  
            index  index.html index.htm;
        }
        #例如:/app 路径为移动H5端
 location ^~app {
            alias   /home/projects/h5_front;
            #当项目的vue-router使用history模式时,刷新界面会空白,或使用有参数的url时候会找不到地址,
            #例如:user/getByid/1 ,使用hash模式无此问题
            try_files $uri $uri/ /index.html;  
            index  index.html index.htm;
        }

		#nginx配置后台代码,当匹配到prod-api时使用代理地址请求
        location /prod-api/{
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header REMOTE-HOST $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://localhost:8080/;  #后台代理地址
        }

        # 避免actuator暴露
        if ($request_uri ~ "/actuator") {
            return 403;
        }
        
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

此时就可以使用http://x.x.x.x:8080访问电脑端的应用,使用http://x.x.x.x:8080/app就可以访问移动端H5的应用,实现了统一的端口访问两个应用

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值