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

后端项目这里使用的.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加上
    Nginx同一个域名下代理后端项目跟多个vue项目_第1张图片
  2. vue.config.js 里面的 publicPath: ‘/admin/’Nginx同一个域名下代理后端项目跟多个vue项目_第2张图片
  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';
    }
      
}

欢迎访问 个人网站

你可能感兴趣的:(nginx,vue,后端)