2014-01-27 17 views
0

我想全球阻止空的用戶代理訪問服務器上的網站。我已經添加了一個http_user_agent拒絕,但它根本不起作用。我正在做對嗎..?這是我的nginx.conf:如何阻止nginx中的空用戶代理?

#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; 
} 
+0

的事情是,這個服務器塊沒有名字,可能不會匹配,除非所有其他服務器不匹配,我不知道'if'適用於'http'情況下,你應該嘗試刪除'服務器'塊,並保留在'http'級別的'if'並嘗試,否則你需要將它添加到你創建的每個'server'上 –

+0

感謝您的幫助 - 我嘗試刪除服務器{}但如果語句不是允許在這種情況下 – Neverlax

+0

那麼你需要在虛擬主機內使用它 –

回答

1

您可以使用ngx_lua模塊來實現這樣的結果。這不是一個官方模塊,但如果你使用的是Ubuntu,你可以通過安裝nginx-extras包來獲得它。一旦你全部搞定,下面的代碼片段添加到您的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(顯然)空字符串和零的情況下,頭並沒有在第一時間發送。

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