How to block empty user agents in nginx?

2019-04-02 22:44发布

问题:

I'm trying to globally block empty user agents from accessing sites on the server. I've added a http_user_agent deny, but it doesn't work at all. Am I doing this right..? Here's my nginx.conf:

#user  nginx;
worker_processes  1;

#error_log  /var/log/nginx/error.log;
#error_log  /var/log/nginx/error.log  notice;
#error_log  /var/log/nginx/error.log  info;

#pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #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;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;
    #tcp_nodelay        on;

    # enable gzip compression
    gzip on;
    gzip_min_length  1100;
    gzip_buffers  4 32k;
    gzip_types    text/plain application/x-javascript text/xml text/css;
    gzip_vary on;
    # end gzip configuration

    server_tokens off;

    server {
        if ($http_user_agent ~* (^$)) { return 403; }
    }

    include /etc/nginx/conf.d/*.conf;
}

回答1:

if ($http_user_agent = "") { return 403; }


回答2:

You can achieve such result by using ngx_lua module. It is not an official module but if you're using Ubuntu, you can get it by installing nginx-extras package. Once you're all set, add the following snippet to your http block

access_by_lua "
  local ua = ngx.req.get_headers()['User-Agent']
  if ua == '' or ua == nil then
    return ngx.exit(ngx.HTTP_FORBIDDEN)
  end";

We check against empty string for empty UA (obviously) and for nil in case the header was not sent in the first place.



标签: nginx