Nginx 禁止某些UA(User Agent)访问

一般来说,我们直接用nginx 的if 语句配合正则表达式就可以了,比如说

# case sensitive matching
if ($http_user_agent ~ (Antivirx|Arian)) {
return 403;
}

# case insensitive matching
if ($http_user_agent ~* (netcrawl|npbot|malicious)) {
return 403;
}

但是当我们需要禁止的user agent lists过长时,用if语句配合正则表达式就不是那么方便,而且性能上也会有影响,因此Nginx官方

多推荐使用map 来代替 if 语句

map $http_user_agent $badagent {
default 0;
~*malicious 1;
~*backdoor 1;
~*netcrawler 1;
~Antivirx 1;
~Arian 1;
~webbandit 1;
}

 if ($badagent) {
return 403;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.