Nginx作为web静态资源服务器——跨域访问

跨站访问

为什么浏览器禁止跨域访问

Nginx跨站访问

Syntax:add_header name value [always];

Default:——

Context:http,server,location,if in location

Access-Control-Allow-Origin     # 通过header判断是否可以跨站访问

演示

创建一个html文件

vi /opt/app/code/test_oringin.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://www.joy.com/1.html",    #如果访问跨域成功,返回success
        success: function(data) {
            alert("sucess!!!");
        },
        error: function() {
            alert("fail!!!,请刷新再试!");        # 如果访问跨域成功,返回“请刷新再试”
        }
    });
});
</script>
<body>
     <h1>测试跨域访问</h1>
</body>
</html>

没有配置语法访问,会返回刷新

配置语法


    location ~ .*.(htm|html) {
        #expires 24h;
        #add_header Access-Control-Allow-Crigin http://www.joy.com;  # 允许跨域访问的域名
        #add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS; # 配置请求方式
        root   /opt/app/code;
    }

再次访问,可以成功跳转到http://www.joy.com/1.html

注意:配置语法中的域名,需要公网的域名

原文地址:https://www.cnblogs.com/joy-sir/p/12162525.html