nginx 配置校验请求头的Referer来做简易的防盗链

需要用到 `valid_referers` 这个配置,可以用在 server 和 location 上,例如:

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
    expires      30d;
    valid_referers none blocked firegod.cn www.firegod.cn;
    if ($invalid_referer) {
        return 403;
    }
}

官方的文档:

Syntax:valid_referers none | blocked | server_names | string ...;
Default:
Context:serverlocation

Specifies the “Referer” request header field values that will cause the embedded $invalid_referer variable to be set to an empty string. Otherwise, the variable will be set to “1”. Search for a match is case-insensitive.

Parameters can be as follows:nonethe “Referer” field is missing in the request header;blockedthe “Referer” field is present in the request header, but its value has been deleted by a firewall or proxy server; such values are strings that do not start with “http://” or “https://”;server_namesthe “Referer” request header field contains one of the server names;arbitrary stringdefines a server name and an optional URI prefix. A server name can have an “*” at the beginning or end. During the checking, the server’s port in the “Referer” field is ignored;regular expressionthe first symbol should be a “~”. It should be noted that an expression will be matched against the text starting after the “http://” or “https://”.

Example:

valid_referers none blocked server_names
               *.example.com example.* www.example.org/galleries/
               ~\.google\.;

Embedded Variables

$invalid_refererEmpty string, if the “Referer” request header field value is considered valid, otherwise “1”.

Leave a Comment

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据