一、什么是主域名,什么是子域名?
主域名又称一级域名或者*域名,由域名主体.域名后缀组成,比如cnblogs.com ;
子域名有二级域名,比如www.cnblogs.com。三级域名,比如home.m.cnblogs.com。
二、基本原理
主域相同,子域不同,可以设置document.domain来解决跨域。
1、在http://www.example.com/a.html和http://sub.example.com/b.html两个文件中都加上document.domain = "example.com";
2、通过a.html文件创建一个iframe,去控制iframe的window,从而进行交互。
三、测试步骤
1、先安装nginx
2、创建a.html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>主域相同子域不同a.html</title> </head> <body> <script> document.domain = 'example.com'; let ifr = document.createElement('iframe'); ifr.src = 'http://sub.example.com/b.html'; ifr.style.display = 'none'; document.body.append(ifr); ifr.onload = function() { let win = ifr.contentWindow; alert(win.data); } </script> </body> </html>
3、创建b.html文件
<script> document.domain = 'example.com'; window.data = '传送的数据:1111'; </script>
4、打开http服务器,通过nginx做域名映射。将example.com映射到localhost:8080,sub.example.com映射到localhost:8081上。
5、打开操作系统下的hosts文件,并添加
127.0.0.1 www.example.com 127.0.0.1 sub.example.com
这样在浏览器打开这两个网址后就会访问本地的服务器。之后打开nginx的配置文件:/usr/local/etc/nginx/nginx.conf,并在http模块里添加:
server{ listen 80; server_name www.example.com; location / { proxy_pass http://127.0.0.1:8080/; } } server{ listen 80; server_name sub.example.com; location / { proxy_pass http://127.0.0.1:8081/; } }
6、最后打开浏览器访问http://www.example.com/a.html就可以看到结果。