传统的jsonp有以下缺点:1 并不是任何官方标准 2 不支持POST请求 3 存在安全漏洞。相比之下使用nginx解决跨域可以很好的规避上面的问题。

nginx解决跨域问题的思路很简单,配置出一个虚拟路径并对这个路径进行拦截,一旦匹配成功就转发到目标地址,由于虚拟路径和当前服务对应的的是同一域名下的不同文件夹,所以不存在跨域的问题。

下面进行演示:下载最新版nginx,笔者使用的是nginx-1.12.2,修改配置文件/config/nginx.conf,这里模拟前后端分离的场景,使用nginx作为前端项目的server,观察server下的location配置,可以发现nginx默认的访问文件的位置为/html,root代表根目录 index代表默认访问的文件:


location / {
            root   html;
            index  index.html index.htm;
        }

在/html文件夹下新建test.htm,用于向后端发起请求,内容如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="http:///js/jquery-easyui-1.4.1/jquery.min.js"></script>
<script type="text/javascript">
	alert($);
	$(function() {
		$.ajax({
			type : "GET",
			url : "http:///jsonp.jsp",//方式1
			//url : "/proxy/html/jsonp.jsp",//方式2
			dataType : "json",
			success:function(data){
				alert(data.abc);
			}
		});
	});
</script>
</head>
<body>

</body>
</html>



修改nginx的配置文件,但是我们想使用域名的形式进项访问,所以需要修改本机的hosts文件:加入以下配置


127.0.0.1 www.quixmart.com #前端域名
127.0.0.1  #后端域名

这样当在浏览器输入域名时,默认访问的是本机地址,完成以后nginx做如下修改:


nginx 跨域 防火墙拦截 nginx怎么解决跨域_nginx 跨域 防火墙拦截







将server_name修改为前端指定的域名,使前端项目可以直接通过域名访问,加入新的server配置使后端项目也能直接通过域名访问:

server {
        listen       80;
        server_name  ;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        location / {
            proxy_pass http://127.0.0.1:8081;
            proxy_connect_timeout 600s;
            proxy_read_timeout 600s;
        }
    }

下面新建后端项目:使用mave构建demo项目,pom文件内容

<project xmlns="http:///POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http:///POM/4.0.0 http:///xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>	
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<!-- jdk配置为1.8 -->
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<configuration>
					<port>8081</port>
					<path>/</path>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

需要使用servlet的依赖,并使用maven提供的tomcat插件启动项目。

建立对应的目录及文件:

nginx 跨域 防火墙拦截 nginx怎么解决跨域_html_02










jsonp.jsp(为了和jsonp的方式进行比较):

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	String callback = request.getParameter("callback");
	if (null == callback) {
		out.print("{\"abc\":123}");
	} else {
		out.print(callback + "({\"abc\":123})");
	}
%>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>demo</display-name>
</web-app>

配置tomcat插件的build

nginx 跨域 防火墙拦截 nginx怎么解决跨域_html_03














nginx 跨域 防火墙拦截 nginx怎么解决跨域_xml_04














bebug启动项目以后,再启动nginx,出现以下页面表示nginx服务正常启动:


nginx 跨域 防火墙拦截 nginx怎么解决跨域_html_05


后台页面正常启动后的访问结果:


nginx 跨域 防火墙拦截 nginx怎么解决跨域_xml_06


下面测试跨域问题:当输入URL:http://www.quixmart.com/test.htm时会访问test.htm并向后端发起ajax请求:


nginx 跨域 防火墙拦截 nginx怎么解决跨域_nginx 跨域 防火墙拦截_07


出现以下页面表示使用script标签的src属性加载js成功,F12进入debug,点击确定以后出现跨域错误:


nginx 跨域 防火墙拦截 nginx怎么解决跨域_html_08


下面在nginx.conf中配置虚拟路径解决跨域:在默认的location下再添加一个location的配置


nginx 跨域 防火墙拦截 nginx怎么解决跨域_nginx_09


其中location后面指定的参数"^~/proxy/html/"是需要拦截路径,匹配成功会停止向下搜索。rewrite后面的第一个参数"^/proxy/html/(.*)$"是需要重写的路径,第二个参数"/$1"是重写后的路径,$1代表正则中的第一个()。break表示匹配成功停止向下搜索。proxy_pass:请求代理到其他主机

http://www.quixmart.com/proxy/html/jsonp.jsp为例:经过拦截后最终的访问地址为:http:///jsonp.jsp。调整test.htm中ajax请求的url,改为方式2通过虚拟路径进行访问,重启nginx,再次访问test.htm,效果如下


nginx 跨域 防火墙拦截 nginx怎么解决跨域_xml_10

nginx 跨域 防火墙拦截 nginx怎么解决跨域_html_11

nginx 跨域 防火墙拦截 nginx怎么解决跨域_nginx 跨域 防火墙拦截_12


成功弹出结果,并没有任何报错信息,跨域问题得到解决~~