nginx限制ip訪問(轉)

weixin_34377065發表於2015-06-15

一、伺服器全侷限IP

#vi nginx.conf

    allow 10.57.22.172;  #允許的IP
    deny all;

 

二、站點限IP

#vi vhosts.conf

站點全侷限IP:
location / {
    index  index.html index.htm index.php;
    allow 10.57.22.172;
    deny all;

    location ~ \.php$ {
        if ( $fastcgi_script_name ~ \..*\/.*php ) {return 403;}
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /var/www/htdocs$fastcgi_script_name;
        include fastcgi_params;
    }
}

站點IP限目錄:
location / {
    index  index.html index.htm index.php;
}

location ^~ /test/ {
    allow 10.57.22.172;
    deny all;

    if ( $fastcgi_script_name ~ \..*\/.*php ) {return 403;}
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  /var/www/htdocs$fastcgi_script_name;
    include fastcgi_params;
}

location ~ \.php$ {
    if ( $fastcgi_script_name ~ \..*\/.*php ) {return 403;}
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  /var/www/htdocs$fastcgi_script_name;
    include fastcgi_params;
}

 

注意事項:

  1. deny 一定要加一個ip,否則直接跳轉到403,不往下執行了;如果403預設頁是同一域名下,會造成死迴圈訪問;

  2. allow的ip段

  從允許訪問的段位從小到大排列,如127.0.0.0/24 下面才能是10.10.0.0/16

  24表示子網掩碼:255.255.255.0

  16表示子網掩碼:255.255.0.0

  8表示子網掩碼:255.0.0.0

  3. deny all;結尾 表示除了上面allow的其他都禁止

如:

           deny 192.168.1.1;
           allow 127.0.0.0/24;
           allow 192.168.0.0/16;
           allow 10.10.0.0/16;
           deny all;

相關文章