温馨提示×

怎样在Nginx中设置防盗链

小樊
40
2025-12-19 21:06:53
栏目: 编程语言

在Nginx中设置防盗链可以通过配置ngx_http_referer_module模块来实现。这个模块允许你根据HTTP请求头中的Referer字段来控制访问权限。以下是一个基本的防盗链配置示例:

  1. 编辑Nginx配置文件: 打开你的Nginx配置文件,通常位于/etc/nginx/nginx.conf/etc/nginx/conf.d/default.conf

  2. 添加防盗链配置: 在server块中添加以下配置:

    server {
        listen 80;
        server_name example.com;
    
        location / {
            # 允许的Referer列表
            valid_referers none blocked server_names *.example.com ~*.example.com;
    
            # 如果Referer不在允许列表中,返回403 Forbidden
            if ($invalid_referer) {
                return 403 "Forbidden";
            }
    
            # 其他配置...
            root /var/www/html;
            index index.html index.htm;
        }
    }
    

    解释:

    • valid_referers指令用于指定允许的Referer。可以设置为none(不允许任何Referer)、blocked(阻止的Referer)、server_names(允许的服务器域名)、*.example.com(允许的子域名)和~*.example.com(允许的子域名,忽略大小写)。
    • if ($invalid_referer)指令用于检查Referer是否有效。如果无效,则返回403 Forbidden状态码。
  3. 测试配置: 在保存配置文件后,运行以下命令测试Nginx配置是否正确:

    sudo nginx -t
    

    如果配置正确,你会看到类似以下的输出:

    nginx: configuration file /etc/nginx/nginx.conf test is successful
    
  4. 重新加载Nginx: 如果配置测试通过,重新加载Nginx以应用新的配置:

    sudo systemctl reload nginx
    

    或者

    sudo nginx -s reload
    

通过以上步骤,你就可以在Nginx中设置基本的防盗链功能。根据你的具体需求,你可以进一步调整和优化配置。

0