1.定义
跨域是指a页面想获取b页面资源,如果a、b页面的协议、域名、端口、子域名不同,所进行的访问行动都是跨域的,而浏览器为了安全问题一般都限制了跨域访问,也就是不允许跨域请求资源。注意:跨域限制访问,其实是浏览器的限制。理解这一点很重要!!!
2.跨域访问示例
假设有两个网站,A网站部署在:http://localhost:7999 即本地ip端口上;B网站部署在:http://localhost:8112 即本地ip端口82上。
现在A网站的页面想去访问B网站的信息,A网站页面的代码如下(这里使用jquery的异步请求):
修改前的js代码:在服务器:localhost:7999服务,访问localhost:8112端口的资源
$(function () { $.ajax({ method:'GET', url:'http://localhost:8112/visual/test/?a=1&b=2', success:function (arg) { alert(arg) } }) });
修改后的ajax请求:
$(function () { $.ajax({ method:'GET', url:'/proxy/visual/test/?a=1&b=2', success:function (arg) { alert(arg) } }) });
nginx的最新配置:
server { listen 7999; server_name localhost; charset utf-8; access_log /val/log/test/.log access; location / { root //usr/local/server/test_service/public; index index.html index.htm index.php; if (!-e $request_filename) { rewrite ^(.*)$ /index.php?s=/$1 last; break; } } #error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } location ~ .php$ { root /usr/local/server/test_service/public; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } location ^~/proxy/{ // 这是需要添加的配置 proxy和上面ajax开头的url一致, 表示拦截/proxy的请求 rewrite ^/proxy/(.*)$ /$1 break; 表示匹配到后就暂停匹配 proxy_pass http://localhost:8112/; 表示将匹配到的转发到你需要访问的服务的主机和端口 } }