nginx反向代理跨域实践

一、nginx相关

  1、正向代理 是一个位于客户端和原始服务器(origin server)之间的服务器,为了从原始服务器取得内容,客户端向代理发送一个请求并指定目标(原始服务器),然后代理向原始服务器转交请求并将获得的内容返回给客户端。客户端必须要进行一些特别的设置才能使用正向代理。

  2、反向代理正好相反,对于客户端而言它就像是原始服务器,并且客户端不需要进行任何特别的设置。客户端向反向代理的命名空间(name-space)中的内容发送普通请求,接着反向代理将判断向何处(原始服务器)转交请求,并将获得的内容返回给客户端,就像这些内容原本就是它自己的一样。

二、通过nginx设置反向代理实现前端跨域(写的有点乱,自己有些东西也不是很清楚)

  1、nginx做web服务器:html中的index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>我是nginx服务器</title>
</head>
<body>
    <p>我是nginx服务器122</p>
</body>
 <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
   <script>
    //请求本地js模拟后台数据
    $.ajax({
      type: "get",
      url: "/apis/index.js",
      dataType: "dataType",
      success: function (res) {
        console.log(res)
      }
    });
   

   //请求豆瓣开放api
   $.ajax({
      type: "get",
      url: "/v2/movie/in_theaters",
      dataType: "dataType",
      success: function (res) {
        console.log(res)
      }
    });
   </script>
</html>

  2、nginx配置文件

worker_processes  1;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
  
    keepalive_timeout  65;

   
  #服务器配置
    server {
     #监听端口 listen 9001; server_name localhost;      #路由入口,这里root表示项目根目录,比如我用nginx做web服务器,根目录就是相对路径下的html location / { root html; index index.html index.htm;
        #下面是代理,如果写了就代表我访问9001可以给我转到下面的地址,前提是,这个地址所在的服务器开启了。 # proxy_pass http://localhost:8082/; }      
      
     #路由匹配一。这里匹配9001端口下的以/apis开始的所有请求,这个是用来请求本地js模拟数据写的 location /apis {
       #重写路由 rewrite ^.+apis/?(.*)$ /$1 break;
       #转发请求 proxy_pass http://top.jiangqi.cn:8081/; } #路由匹配二。这里是用来测试豆瓣开放api写的 location /v2 { proxy_pass https://api.douban.com/v2/; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
 
原文地址:https://www.cnblogs.com/helloNico/p/10685042.html