允许跨域访问

#盗链就是由我的网站向你的网站发起get获取资源的请求

#跨域访问由我的网站向你的网站发起http的链接请求

1)配置被跨域的网站

[root@web02 /etc/nginx/conf.d]# vim beikuayu.conf
server {
    listen 80;
    server_name linux.beikuayu.com;

    location / {
        root /code/beikuayu;
        index index.html;
    }
}

#创建站点
[root@web02 ~]# echo "bei kua yu de wang zhan" > /code/beikuayu/index.html

2)配置跨域的网站

[root@web01 ~]# vim /etc/nginx/conf.d/kuayu.conf
server {
    listen 80;
    server_name linux.kuayu.com;

    location / {
        root /code/kuayu;
        index index.html;
    }
}

#配置站点
[root@web01 ~]# mkdir /code/kuayu
[root@web01 ~]# vim /code/kuayu/index.html
<html lang="en">
<head>
        <meta charset="UTF-8" />
        <title>测试ajax和跨域访问</title>
        <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function(){
        $.ajax({
        type: "GET",
        url: "http://linux.beikuayu.com",
        success: function(data) {
                alert("sucess 卧槽 卧槽 卧槽 成功了!!!");
        },
        error: function() {
                alert("fail!!,跨不过去啊,不让进去啊,只能蹭蹭!");
        }
        });
});
</script>
        <body>
                <h1>测试跨域访问</h1>
        </body>
</html>

3)配置hosts

[root@web01 ~]# vim /etc/hosts
10.0.0.7 linux.beikuayu.com
10.0.0.8 linux.beikuayu.com

[root@web02 ~]# vim /etc/hosts
10.0.0.7 linux.beikuayu.com
10.0.0.8 linux.beikuayu.com

#配置windows的hosts
10.0.0.7 linux.kuayu.com

4)配置允许跨域访问

[root@web02 /etc/nginx/conf.d]# vim beikuayu.conf 
server {
    listen 80;
    server_name linux.beikuayu.com;
    root /code/beikuayu;
    index index.html;

    location ~* .html$ {
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
    }
}
原文地址:https://www.cnblogs.com/chenlifan/p/13652127.html