Nginx作为静态资源web服务-跨站访问

一、跨域访问

1、什么是跨域?

参看我的另一篇博客(https://www.cnblogs.com/chrdai/p/11280895.html

Nginx作为静态资源web服务-跨站访问

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

不安全,容易出现CSRF攻击。

a、什么是CSRF攻击呢?

CSRF(Cross-site request forgery)攻击就是跨站式攻击。原理如下:

Nginx作为静态资源web服务-跨站访问

当用户去访问正规网站(网站A)时,不小心点到了恶意网站B,网站B通过http Response向该用户发送一些带有恶意的请求,让用户在去请求网站A,这样就形成了跨站访问,出于安全考虑,浏览器对这种跨站请求默认是阻止的。

3、Nginx如何打开跨站访问?

配置语法

Syntax:add_header name value [always]
Default:-
Context:http,server,locatin,if in location;

这里的 value 就是待跨站的网站地址,如果为 “ * ” ,就意味着允许所有的网站都可以跨站访问本站点,出于安全考虑,建议只填写需要用到的站点。

示例:

Nginx作为静态资源web服务-跨站访问

location ~ .*\.(htm|html)$ {
add_header Access-Control-Allow-Origin 192.168.0.133:;
add_header Access-Control-Allow-Mehtods GET,POST;
root /opt/app/code1;
}

下面是一段儿测试 ajax 跨站访问的示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test ajax CORS</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<p>Test ajax CORS</p> <script>
$(function(){
$.ajax({
url: '192.168.0.133:81',
method: 'POST',
dataType: 'json',
success: function(data){
alert('success!');
},
error: function(data){
alert('fail!');
},
});
});
</script>
</body>

本文为袋鼠学习中的总结,如有转载请注明出处:https://www.cnblogs.com/chrdai/protected/p/11336123.html

上一篇:Struts2 2.5.12的问题


下一篇:pfile,spfile 初始化参数文件顺序【weber出品】