Nginx同一个域名下代理后端项目跟多个vue项目

本文详细介绍了如何为.NET Core API项目和Vue前端应用设置Nginx代理,涉及history模式、跨域请求及路径重写,包括Vue路由调整、Vue公共路径配置、API代理和全站路径处理技巧。

后端项目这里使用的.net core api

配置如下

  location / {
       proxy_pass http://localhost:6006;
       proxy_http_version 1.1;
       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection keep-alive;
       proxy_cache_bypass $http_upgrade;

       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      
       add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
       add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
    }

vue 项目因为是同一个域名下所以要做一下更改

  1. 路由里面修mode改成 history,base同时加上 /project/
export default new Router({
    mode: 'history',
    base: "/admin/",
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRouterMap
})
  1. public inde.html 里面 head加上
    在这里插入图片描述
  2. vue.config.js 里面的 publicPath: ‘/admin/’在这里插入图片描述
  3. nginx里面配置
    需要注意的是一般情况下:try_files 我们只配置 $uri $uri/ /index.html这几个但是同一个域名下的话,如果路由有几段时(如:http://xxxx/admin/account/settings/base)需要加上 $uri/admin 不然会出现无法访问的情况
 location ^~ /admin{
       alias   /var/www/car/admin/;
       index index.html index.htm;  
       try_files $uri $uri/ /index.html $uri/admin;       
    }
    #代理api项目	
   location /api{
        rewrite ^.+/api/?(.*)$ /$1 break;
        include uwsgi_params;
        proxy_pass http://localhost:6006; 
  }

完整版nginx配置

server {
    listen 80;
    server_name  www.ztan.net;
    location ^~ /admin{
       alias   /var/www/car/admin/;
       index index.html index.htm;  
       try_files $uri $uri/ /index.html $uri/admin;       
    }
     #反向代理vue 项目接口	
   location /api{
        rewrite ^.+/api/?(.*)$ /$1 break;
        include uwsgi_params;
        proxy_pass http://localhost:6006; 
  }
    location / {
       proxy_pass http://localhost:6006;
       proxy_http_version 1.1;
       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection keep-alive;
       proxy_cache_bypass $http_upgrade;

       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      
       add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
       add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
    }
      
}

欢迎访问 个人网站

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值