一段万能的nginx接口实现反向代理配置

1、什么是代理服务器

代理服务器,客户机在发送请求时,不会直接发送给目的主机,而是先发送给代理服务器,代理服务接受客户机请求之后,再向主机发出,并接收目的主机返回的数据,存放在代理服务器的硬盘中,再发送给客户机。

2、为什么要使用代理服务器

1)提高访问速度  

由于目标主机返回的数据会存放在代理服务器的硬盘中,因此下一次客户再访问相同的站点数据时,会直接从代理服务器的硬盘中读取,起到了缓存的作用,尤其对于热门站点能明显提高请求速度。

2)防火墙作用   

由于所有的客户机请求都必须通过代理服务器访问远程站点,因此可在代理服务器上设限,过滤某些不安全信息。

3)通过代理服务器访问不能访问的目标站点 

互联网上有许多开发的代理服务器,客户机在访问受限时,可通过不受限的代理服务器访问目标站点,通俗说,我们使用的翻墙浏览器就是利用了代理服务器,虽然不能出国,但也可直接访问外网。

反向代理 VS 正向代理

1、什么是正向代理?什么是反向代理?

正向代理,架设在客户机与目标主机之间,只用于代理内部网络对Internet的连接请求,客户机必须指定代理服务器,并将本来要直接发送到Web服务器上的http请求发送到代理服务器中。

反向代理服务器架设在服务器端,通过缓冲经常被请求的页面来缓解服务器的工作量,将客户机请求转发给内部网络上的目标服务器;并将从服务器上得到的结果返回给Internet上请求连接的客户端,此时代理服务器与目标主机一起对外表现为一个服务器。

2、反向代理有哪些主要应用?

现在许多大型web网站都用到反向代理。除了可以防止外网对内网服务器的恶性攻击、缓存以减少服务器的压力和访问安全控制之外,还可以进行负载均衡,将用户请求分配给多个服务器。

作为前端开发,每次调试接口,把代码发到测试服务器,是很费时费事的一件事情。

为了提高效率,想到了nginx反向代理来解决这一问题。

接口地址:
test.com

访问地址:
localhost

最核心的问题就是,登录时,无法写入cookie的问题,为了解决这个问题,走了不少弯路。

  worker_processes 1;  events {    worker_connections 1024;  }  http {    include    mime.types;    default_type application/octet-stream;    sendfile   on;    keepalive_timeout 10;    server {      listen 80;      server_name localhost;            location =/ {        add_header X-Frame-Options SAMEORIGIN;        root    D:/workspace/;        index index.html;      }        location ~* .(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css|swf|woff|woff2|ttf|json|svg|cur|vue|otf|eot)$ {        charset   utf-8;        root    D:/workspace/;        expires   3d;      }            location = /socket/v2 {        proxy_pass  http://test.com;        proxy_redirect off;        proxy_http_version 1.1;        proxy_set_header Upgrade $http_upgrade;        proxy_set_header Connection "upgrade";        proxy_set_header Host test.com;        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_connect_timeout 30;        proxy_send_timeout 30;        proxy_read_timeout 60;        proxy_buffer_size 256k;        proxy_buffers 4 256k;      }            location / {        proxy_pass  http://test.com;        proxy_set_header Cookie $http_cookie;        proxy_cookie_domain test.com localhost;        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;        proxy_set_header Host test.com;        proxy_set_header X-Real-IP $remote_addr;        proxy_set_header REMOTE-HOST $remote_addr;      }    }  }

核心代码在三行代码上:

  proxy_set_header Cookie $http_cookie;  proxy_cookie_domain test.com localhost;  proxy_set_header Host test.com;

具体解释我也是一知半解:

  • 第一个是携带cookie,
  • 第二个设置cookie 的 domain
  • 第三个 设置真实的host

重要提示:以上3个的顺序不要颠倒,否则代理失败,我也不知道为什么。

如何在手机上调试呢?

手机上不可能直接访问localhost,可以把手机和电脑连接到同一个网段,使用电脑的ip进行访问。
但是这里只代理了localhost,并没有代理电脑的ip

所以,需要把是上面的server{...}拷贝一份,只需要把里面的localhost全部改成你的电脑ip就可以了,最终代码:

  worker_processes 1;  events {    worker_connections 1024;  }  http {    include    mime.types;    default_type application/octet-stream;    sendfile   on;    keepalive_timeout 10;    server {      listen 80;      server_name localhost;            location =/ {        add_header X-Frame-Options SAMEORIGIN;        root    D:/workspace/;        index index.html;      }        location ~* .(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css|swf|woff|woff2|ttf|json|svg|cur|vue|otf|eot)$ {        charset   utf-8;        root    D:/workspace/;        expires   3d;      }            location = /socket/v2 {        proxy_pass  http://test.com;        proxy_redirect off;        proxy_http_version 1.1;        proxy_set_header Upgrade $http_upgrade;        proxy_set_header Connection "upgrade";        proxy_set_header Host test.com;        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_connect_timeout 30;        proxy_send_timeout 30;        proxy_read_timeout 60;        proxy_buffer_size 256k;        proxy_buffers 4 256k;      }            location / {        proxy_pass  http://test.com;        proxy_set_header Cookie $http_cookie;        proxy_cookie_domain test.com localhost;        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;        proxy_set_header Host test.com;        proxy_set_header X-Real-IP $remote_addr;        proxy_set_header REMOTE-HOST $remote_addr;      }    }    server {      listen 8080;      server_name xx.xx.xx.xx;            location =/ {        add_header X-Frame-Options SAMEORIGIN;        root    D:/workspace/;        index index.html;      }        location ~* .(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css|swf|woff|woff2|ttf|json|svg|cur|vue|otf|eot)$ {        charset   utf-8;        root    D:/workspace/;        expires   3d;      }            location = /socket/v2 {        proxy_pass  http://test.com;        proxy_redirect off;        proxy_http_version 1.1;        proxy_set_header Upgrade $http_upgrade;        proxy_set_header Connection "upgrade";        proxy_set_header Host test.com;        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_connect_timeout 30;        proxy_send_timeout 30;        proxy_read_timeout 60;        proxy_buffer_size 256k;        proxy_buffers 4 256k;      }            location / {        proxy_pass  http://test.com;        proxy_set_header Cookie $http_cookie;        proxy_cookie_domain test.com xx.xx.xx.xx;        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;        proxy_set_header Host test.com;        proxy_set_header X-Real-IP $remote_addr;        proxy_set_header REMOTE-HOST $remote_addr;      }    }  }

访问方法:http://xx.xx.xx.xx:8080 即可

如果是打包工具生成增这个配置的话,可以用nodejs动态获取你电脑的ip

  function getIPAdress() {       var interfaces = require('os').networkInterfaces();       for (var devName in interfaces) {            var iface = interfaces[devName];            for (var i = 0; i < iface.length; i++) {                 var alias = iface[i];                 if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {                      return alias.address;        }            }       }   }  

所以,这里贴出来一个动态生成nginx.config的工具

  function buildNginxConfig(config) {      function getIPAdress() {         var interfaces = require('os').networkInterfaces();         for (var devName in interfaces) {              var iface = interfaces[devName];              for (var i = 0; i < iface.length; i++) {                   var alias = iface[i];                   if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {                        return alias.address;                   }              }         }     }    var cwd = process.cwd().replace(//g, '/') + '/app';    var protocol = /https|443/.test(config.ip) ? 'https' : 'http';      var servers = [{      browserIp: 'localhost',      port: 80,      root: cwd,      serverIp: config.ip,      protocol: protocol,    }, {      browserIp: getIPAdress(),      port: 8080,      root: cwd,      serverIp: config.ip,      protocol: protocol,    }].map(function(item) {      return `    server {      listen ${item.port};      server_name ${item.browserIp};            location =/ {        add_header X-Frame-Options SAMEORIGIN;        root    ${item.root};        index index.html;      }        location ~* .(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css|swf|woff|woff2|ttf|json|svg|cur|vue|otf|eot)$ {        charset   utf-8;        root    ${item.root};        expires   3d;      }            location = /socket/v2 {        proxy_pass  ${item.protocol}://${item.serverIp};        proxy_redirect off;        proxy_http_version 1.1;        proxy_set_header Upgrade $http_upgrade;        proxy_set_header Connection "upgrade";        proxy_set_header Host ${item.serverIp};        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_connect_timeout 30;        proxy_send_timeout 30;        proxy_read_timeout 60;        proxy_buffer_size 256k;        proxy_buffers 4 256k;      }            location / {        proxy_pass  ${item.protocol}://${item.serverIp};        proxy_set_header Cookie $http_cookie;        proxy_cookie_domain ${item.serverIp} ${item.browserIp};        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;        proxy_set_header Host ${item.serverIp};        proxy_set_header X-Real-IP $remote_addr;        proxy_set_header REMOTE-HOST $remote_addr;      }    }`;    }).join('n');    var str = `worker_processes 1;  events {    worker_connections 1024;  }  http {    include    mime.types;    default_type application/octet-stream;    sendfile   on;    keepalive_timeout 10;    ${servers}  }`;      return str;  }    exports = module.exports = buildNginxConfig;    

有了这个万能反向代理,可以随心所欲的玩转任何网站接口了

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支Fatmouse

参与评论