温馨提示×

Nginx怎样实现防盗链

小樊
44
2025-12-18 19:43:23
栏目: 编程语言

Nginx可以通过配置来实现防盗链功能,以下是具体的步骤:

1. 配置防盗链

方法一:使用valid_referers指令

在Nginx配置文件中,可以使用valid_referers指令来指定允许访问资源的来源。如果请求的来源不在允许列表中,则返回403 Forbidden状态码。

server {
    listen 80;
    server_name example.com;

    location /protected/ {
        valid_referers none blocked server_names example.com www.example.com;
        if ($invalid_referer) {
            return 403 "Forbidden";
        }
        # 其他配置...
    }
}

方法二:使用ngx_http_referer_module模块

这个模块提供了更灵活的防盗链配置选项。

server {
    listen 80;
    server_name example.com;

    location /protected/ {
        referer http://example.com http://www.example.com;
        if ($invalid_referer) {
            return 403 "Forbidden";
        }
        # 其他配置...
    }
}

2. 配置缓存控制

为了防止盗链者通过缓存机制绕过防盗链检查,可以配置缓存控制头。

location /protected/ {
    valid_referers none blocked server_names example.com www.example.com;
    if ($invalid_referer) {
        return 403 "Forbidden";
    }

    add_header Cache-Control "no-cache, no-store, must-revalidate";
    add_header Pragma "no-cache";
    add_header Expires "0";
    # 其他配置...
}

3. 使用签名URL

对于动态生成的内容,可以使用签名URL的方式来实现防盗链。Nginx本身不直接支持签名URL,但可以通过第三方模块或自定义脚本来实现。

使用第三方模块(如ngx_http_auth_request_module

这个模块可以用来进行复杂的认证和授权,包括基于签名的URL验证。

location /protected/ {
    auth_request /auth;
    # 其他配置...
}

location = /auth {
    internal;
    proxy_pass http://auth-server/validate;
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
    proxy_set_header X-Original-URI $request_uri;
}

auth-server中,可以实现签名验证逻辑。

4. 监控和日志

为了更好地监控和调试防盗链配置,可以启用详细的日志记录。

http {
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;
    error_log /var/log/nginx/error.log debug;
}

通过以上步骤,可以有效地实现Nginx的防盗链功能,保护你的资源不被非法访问。

0