Nginx 反向代理解决跨域问题

130 阅读1分钟

最近在项目中遇到了跨域相关的问题,注意:跨域限制访问,其实是浏览器的限制,比较了几种跨域解决方案,决定采取Nginx的方式来解决。

下面发一段我实际项目中的配置供参考,其中 10.12.1.210 为Nginx所在机器的IP地址,80端口是Nginx监听端口(可以同时监听多个端口),代码如下:

server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  localhost;

        location / {
		root /usr/share/nginx/html/PaaS/;
	        try_files $uri /index.html;
		index index.html;
        }

	location /oas-cloud {
	        proxy_set_header X-Real-IP $remote_addr;
		proxy_pass http://10.12.1.210:30003/oas-cloud;
	}

	location /zuul {
		proxy_set_header X-Real-IP $remote_addr;
		proxy_pass http://10.12.1.210:30003/zuul;
	}

	location /upload {
		proxy_set_header X-Real-IP $remote_addr;
		proxy_pass http://127.0.0.1:9010/upload;
	}
 
        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
}

server {
  listen    9010;
  server_name localhost;
  charset utf-8;

  include /etc/nginx/default.d/*.conf;
  location / {
	  root /usr/local/oas/file;
	  sendfile on;
	  autoindex on;
	  autoindex_exact_size off;
	  autoindex_localtime on;
  }
}

配置解释:

1.由配置信息可知,我们让nginx监听localhost的80端口,不论是请求A接口还是请求B接口的访问方式都是经过localhost的80端口进行访问。

2.我们特殊配置了一个“/apis”目录的访问,并且对url执行了重写,最后使以“/apis”开头的
地址都转到“http://localhost:82”进行处理,不同的接口可以通过前缀区分。

Nginx反向代理的好处是不需要目标服务器配合,不过需要你搭建一个中转nginx服务器用于转发请求。

到此 Nginx 跨域解决方案(CORS跨域配置、端口转发)介绍完成。