这篇文章给大家介绍的内容是关于nginx如何实现跨域访问?nginx跨域访问的实现,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
跨域是指从一个域名的网页去请求另一个域名的资源。比如从 www.a.com 页面去请求 www.b.com 的资源。

浏览器一般默认会禁止跨域访问。因为不安全,容易出现 CSRF(跨站请求伪造)攻击。
Nginx通过添加 Access-Control-Allow-Origin、Access-Control-Allow-Methods、Access-Control-Allow-Headers 等HTTP头信息的方式控制浏览器缓存。
"Access-Control-Allow-Origin" 设置允许发起跨域请求的网站
"Access-Control-Allow-Methods" 设置允许发起跨域请求请求的HTTP方法
"Access-Control-Allow-Headers" 设置允许跨域请求包含 Content-Type头
Syntax: add_header name value [always]; Default: — Context: http, server, location, if in location
# 配置网站www.a.com
server {
server_name www.a.com;
root /vagrant/a;
# 允许 http://www.b.com 使用 GET,POST,DELETE HTTP方法发起跨域请求
add_header Access-Control-Allow-Origin http://www.b.com;
add_header Access-Control-Allow-Method GET,POST,DELETE;
}
# 配置网站www.b.com
server {
server_name www.b.com;
root /vagrant/b;
}
# 配置网站www.c.com
server {
server_name www.c.com;
root /vagrant/c;
}/vagrant/a/a.txt、/vagrant/b/index.html、/vagrant/c/index.html 文件vim /vagrant/a/a.txt
Hello,I'm a!
/vagrant/b/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ajax跨站访问b</title>
</head>
<body>
<h1>Ajax跨站访问b - </h1>
</body>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(function(){
$.ajax({
url: "http://www.a.com/a.txt",
type: "GET",
success: function (data) {
$('h1').append(data);
},
error: function (data) {
$('h1').append('请求失败!');
}
});
})
</script>
</html>/vagrant/c/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ajax跨站访问c</title>
</head>
<body>
<h1>Ajax跨站访问c - </h1>
</body>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(function(){
$.ajax({
url: "http://www.a.com/a.txt",
type: "GET",
success: function (data) {
$('h1').append(data);
},
error: function (data) {
$('h1').append('请求失败!');
}
});
})
</script>
</html>windows: C:\Windows\System32\drivers\etc\hosts
linux: /etc/hosts
添加如下内容,并保存(192.168.33.88为笔者虚拟机的IP,需自行替换为自己的IP):
192.168.33.88 www.a.com 192.168.33.88 www.b.com 192.168.33.88 www.c.com
http://www.b.com/index.html 和 http://www.c.com/index.htmlhttp://www.b.com/index.html
Ajax跨站访问b - Hello,I'm a!
http://www.c.com/index.html
Ajax跨站访问c - 请求失败!
打开浏览器的开发者模式Console,还可以发现 http://www.c.com/index.html 的页面出现报错:
Failed to load http://www.a.com/a.txt: The 'Access-Control-Allow-Origin' header has a value 'http://www.b.com' that is not equal to the supplied origin. Origin 'http://www.c.com' is therefore not allowed access.
相关文章推荐:
Nginx作为静态资源web服务来控制浏览器缓存以及实现防盗链
以上就是Nginx如何实现跨域访问?Nginx跨域访问的实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号