服务器之家:专注于服务器技术及软件下载分享
分类导航

云服务器|WEB服务器|FTP服务器|邮件服务器|虚拟主机|服务器安全|DNS服务器|服务器知识|Nginx|IIS|Tomcat|

服务器之家 - 服务器技术 - Nginx - Nginx跨域访问场景配置和防盗链详解

Nginx跨域访问场景配置和防盗链详解

2019-09-20 22:47Crazymagic Nginx

这篇文章主要介绍了Nginx跨域访问场景配置和防盗链详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

跨域访问控制

跨域访问

Nginx跨域访问场景配置和防盗链详解

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

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

Nginx跨域访问场景配置和防盗链详解

如果黑客控制的网站B在响应头里添加了让客户端去访问网站A的恶意信息,就会出现CSRF攻击

Nginx如何配置跨域访问

add_header语法

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

语法解释:

  • add_header name value [always];
  • name 表示响应头返回的key
  • value 表示响应头返回的key对应的value
  • add_header跨域配置
location ~ .*\.(htm|html)$ {
  add_header Access-Control-Allow-Origin *;
  add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
  root /opt/app/code;
}
  

防盗链

防盗链目的

  • 防止资源被盗用。
  • 防止非正常用户访问,占用网站资源,影响网站性能,势必影响正常用户访问

基于http_referer防盗链配置模块

ngx_http_referer_module模块用于阻止对“Referer”头字段中具有无效值的请求访问站点。

举例

valid_referers none blocked server_names
 
        *.example.com example.* www.example.org/galleries/
 
        ~\.google\.;
 
if ($invalid_referer) {
 
  return 403;
 
}

referer_hash_bucket_size语法

  • Syntax: referer_hash_bucket_size size;  
  • Default: referer_hash_bucket_size 64;
  • Context: server, location

语法解释:

referer_hash_bucket_size size;表示设置有效引用散列表的存储区大小。

referer_hash_max_size 语法

  • Syntax: referer_hash_max_size size;
  • Default: referer_hash_max_size 2048;
  • Context: server, location

语法解释:

referer_hash_max_size size;表示设置有效引用者哈希表的最大大小。

valid_referers语法

  • Syntax: valid_referers none | blocked | server_names | string ...;
  • Default: —
  • Context: server, location

语法解释:

  • valid_referers none | blocked | server_names | string ...;
  • none表示请求标头中缺少“Referer”字段;
  • blocked表示“Referer”字段出现在请求标头中,但其值已被防火墙或代理服务器删除; 这些值是不以“http://”或“https://”开头的字符串;
  • server_names 表示“Referer”请求头字段包含一个服务器名称;
  • string 表示定义服务器名称和可选的URI前缀。 服务器名称的开头或结尾可以包含“*”。 在检查期间,“Referer”字段中的服务器端口被忽略;

防盗链小案例

touch test_referer.html (在 /op/app/code 目录下)

<html>
<head>
  <meta charset="utf-8">
  <title>imooc1</title>
</head>
<body style="background-color:red;"><br data-filtered="filtered">   <h1>张彪</h1>
  <img src="http://192.168.1.112/wei.png"/>
</body>
</html>

Nginx跨域访问场景配置和防盗链详解

配置防盗链如果不是从 www.zhangbiao.com 域名转来的就会报错

location ~ .*\.(jpg|gif|png)$ {
  valid_referers none blocked www.zhangbiao.com;
  if ($invalid_referer) {
    return 403;
  }
  root /opt/app/code/images;
}
location ~ /test_refer.html {
  root /opt/app/code;
 
}

访问

http://192.168.1.112/test_refer.html

Nginx跨域访问场景配置和防盗链详解

访问

http://www.zhangbiao.com/test_refer.html

Nginx跨域访问场景配置和防盗链详解

允许其他网站访问自己网站资源配置

Nginx跨域访问场景配置和防盗链详解

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

延伸 · 阅读

精彩推荐