【问题标题】:How to block empty user agents in nginx?如何阻止 nginx 中的空用户代理?
【发布时间】:2014-02-18 22:40:46
【问题描述】:

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

【问题讨论】:

  • 问题是,这个服务器块没有名称,可能不会匹配,除非所有其他服务器都无法匹配,我不知道if 是否适用于http 上下文,你应该尝试删除server 块并将if 保持在http 级别并尝试,否则您需要将其添加到您创建的每个server
  • 感谢您的帮助 - 我尝试删除服务器{},但在该上下文中不允许使用 if 语句
  • 那你需要在虚拟主机里面使用它

标签: nginx


【解决方案1】:
if ($http_user_agent = "") { return 403; }

【讨论】:

    【解决方案2】:

    你可以通过使用 ngx_lua 模块来达到这样的效果。它不是官方模块,但如果你使用的是 Ubuntu,你可以通过安装 nginx-extras 包来获得它。一切就绪后,将以下 sn-p 添加到您的 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,以防一开始没有发送标头。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-04
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 2011-11-14
      • 1970-01-01
      相关资源
      最近更新 更多