日期:2014-05-16  浏览次数:20941 次

(apache)mod_proxy 和 mod_rewrite实现js跨域
项目中用到了,于是搞了几多时间,还是没太明白,只是会基本用法,由于后来项目换实现方式,不存在跨域问题了,就没研究了,这里记录下,已备所需
废话不多说了,这里只讲这个,其他方式自己去试,直接先上两篇参考
1、(两种方式的基本配置)
http://www.joywebsite.com/2011/01/how-to-bypass-cross-domain-restrictions-by-apache/
2、(mod_rewrite官方文档中文详解)
http://man.chinaunix.net/newsoft/ApacheManual/misc/rewriteguide.html


下面是我根据上面2篇参考自己写的:
1、下载apache代理服务器 http://apache.etoak.com//httpd/binaries/win32/httpd-2.2.21-win32-x86-no_ssl.msi
2、安装后,打开安装目录下conf/httpd.conf文件
3、去掉注释
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule rewrite_module modules/mod_rewrite.so
在最下面增加:
<VirtualHost *:80>        

<Location /web2>
  SetHandler proxy-server
  order allow,deny
  Allow from all
</Location>
RewriteEngine on
RewriteRule ^/web1/(.*)$ http://localhost:8080/web1/$1 [L,R=301,P,NC]
RewriteRule ^/web2/(.*)$ http://localhost:8082/web2/$1 [L,R=301,P,NC]
</VirtualHost>

这样配置就完成了,解释下上面两个 rewriterule 的含义,其余的找上面给出的两篇资料参考
上面的web1和web2其实是两个项目部署在不同的tomcat中,端口分别为8080和8082

web1中的index.jsp文件:
<html>
	<head>
	</head>
	<script type="text/javascript">
  	function cc(){
  		window.frames['ifr'].test('web1');
  	}
  </script>
	<body>
		<input id="btn" type="button" value="ADD" onclick="javascript: cc();" />
		<iframe name="ifr" src="http://localhost/web2/index.jsp" width=800 height=600></iframe>
	</body>
</html>


web2中的index.jsp文件:
<html>
<script type="text/javascript">
function test(s){
	var div = document.createElement("div");
	div.innerHTML = s;
	document.body.appendChild(div);
}
</script>
<body>
web2
</body>
</html>


注:
访问web1中的index页面必须要用 http://localhost/web1/index.jsp 才会解决跨域问题,必须要和iframe的src(localhost)相同,IP同理