如何阻止nginx中的空用户代理?

如何阻止nginx中的空用户代理?,nginx,Nginx,我正在尝试全局阻止空用户代理访问服务器上的站点。我添加了一个http\u用户\u代理拒绝,但它根本不起作用。我这样做对吗。。?这是我的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

我正在尝试全局阻止空用户代理访问服务器上的站点。我添加了一个http\u用户\u代理拒绝,但它根本不起作用。我这样做对吗。。?这是我的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;
}

您可以通过使用ngx_lua模块来实现这样的结果。这不是一个正式的模块,但是如果你使用Ubuntu,你可以通过安装nginx附加软件包来获得它。设置完毕后,将以下代码段添加到http块

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

我们根据空字符串检查空UA,如果头没有首先发送,则检查nil。

问题是,此服务器块没有名称,可能不会匹配,除非所有其他服务器都无法匹配,我不知道是否在http上下文中工作,您应该尝试删除服务器块,并将if保持在http级别,然后重试,否则您需要将其添加到您创建的每台服务器感谢您的帮助-我尝试删除服务器{},但是如果该上下文中不允许使用语句,那么您需要在虚拟主机中使用它
if ($http_user_agent = "") { return 403; }