NginxÔõÑùʵÏÖ»ùÓÚÇëÇóȪԴIPµÄ»á¼û¿ØÖÆÉèÖÃ
NginxÔõÑùʵÏÖ»ùÓÚÇëÇóȪԴIPµÄ»á¼û¿ØÖÆÉèÖã¬ÐèÒªÏêϸ´úÂëʾÀý
ÔÚÍøÂçÓ¦Óÿª·¢ÖУ¬±£»¤Ð§ÀÍÆ÷ÃâÊܶñÒâ¹¥»÷ÊǺÜÊÇÖ÷ÒªµÄÒ»»·¡£Ê¹ÓÃNginx×÷Ϊ·´ÏòÊðÀíЧÀÍÆ÷£¬ÎÒÃÇ¿ÉÒÔͨ¹ýÉèÖÃIP»á¼û¿ØÖÆ£¬ÏÞÖÆÌض¨IPµØµãµÄ»á¼ûȨÏÞ£¬ÒÔÌá¸ßЧÀÍÆ÷µÄÇå¾²ÐÔ¡£±¾ÎĽ«ÏÈÈÝÔõÑùÔÚNginxÖÐʵÏÖ»ùÓÚÇëÇóȪԴIPµÄ»á¼û¿ØÖÆÉèÖ㬲¢ÌṩÏêϸµÄ´úÂëʾÀý¡£
Ê×ÏÈ£¬ÎÒÃÇÐèÒª±à¼NginxµÄÉèÖÃÎļþ¡£Ò»Ñùƽ³£ÇéÐÎÏ£¬¸ÃÎļþλÓÚ/etc/nginx/nginx.conf¡£ÔÚ¸ÃÎļþÖУ¬ÎÒÃÇ¿ÉÒÔÕÒµ½Ò»¸öÃûΪ¡°http¡±µÄ¿é£¬ÆäÖаüÀ¨ÁËÈ«¾ÖµÄNginxÉèÖá£ÎÒÃÇÐèÒªÔڸÿéÖÐÌí¼ÓÒÔÏ´úÂ룺
http { # ½ç˵һ¸öÃûΪ¡°block_ip¡±µÄmap£¬ÓÃÓÚ´æ´¢ÐèÒªÆÁÕϵÄIPµØµã map $remote_addr $block_ip { default 0; # ĬÈÏÇéÐÎÏ£¬²»ÆÁÕÏÈκÎIPµØµã 192.168.0.100 1; # ÐèÒªÆÁÕϵÄIPµØµã£¬ÖµÉèΪ1 192.168.0.101 1; # ÐèÒªÆÁÕϵÄIPµØµã£¬ÖµÉèΪ1 } # ½ç˵һ¸öÃûΪ¡°block_ips¡±µÄ±äÁ¿£¬Í¨¹ýÄÚ²¿Öض¨ÏòµÄ·½·¨Ê¹Óá°block_ip¡±¾ÙÐÐÅÐ¶Ï set $block_ips ""; if ($block_ip = 1) { set $block_ips "block"; } # ÔÚserver¿éÖÐÌí¼Ó»á¼û¿ØÖÆÉèÖã¬Ö»ÔÊÐíûÓб»ÆÁÕϵÄIPµØµã»á¼û server { listen 80; server_name example.com; # Ìí¼Ó¶Ôblock_ips±äÁ¿ÖµµÄÅÐ¶Ï if ($block_ips = "block") { return 403; } } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊö´úÂëÖУ¬ÎÒÃÇÊ×ÏȽç˵ÁËÒ»¸öÃûΪ¡°block_ip¡±µÄmap£¬ÓÃÓÚ´æ´¢ÐèÒªÆÁÕϵÄIPµØµã¡£Ä¬ÈÏÇéÐÎÏ£¬ÉèÖÃΪ0£¬ÌåÏÖ²»ÆÁÕÏÈκÎIPµØµã¡£ÎÒÃÇ¿ÉÒÔƾ֤ÐèÒª£¬½«Ìض¨µÄIPµØµãÉèΪ1£¬ÌåÏÖÐèÒªÆÁÕϸÃIPµØµã¡£
½ÓÏÂÀ´£¬ÎÒÃǽç˵ÁËÒ»¸öÃûΪ¡°block_ips¡±µÄ±äÁ¿£¬Í¨¹ýÄÚ²¿Öض¨ÏòµÄ·½·¨Ê¹Óá°block_ip¡±¾ÙÐÐÅжϡ£Ê×ÏÈ£¬ÎÒÃǽ«¸Ã±äÁ¿ÉèÖÃΪ¿Õ¡£È»ºó£¬Í¨¹ýifÓï¾äÅжϣ¬¡°block_ip¡±µÄÖµÊÇ·ñ¼´ÊÇ1¡£ÈôÊÇÊÇ£¬½«¡°block_ips¡±ÉèÖÃΪ¡°block¡±¡£
×îºó£¬ÔÚserver¿éÖÐÌí¼ÓÁË»á¼û¿ØÖÆÉèÖá£ÎÒÃÇʹÓÃlistenÖ¸ÁîÖ¸¶¨¼àÌýµÄ¶Ë¿ÚºÅ£¬Ê¹ÓÃserver_nameÖ¸ÁîÖ¸¶¨ÓòÃû»òIPµØµã¡£ÔÚifÓï¾äÖУ¬ÎÒÃÇÅжϡ°block_ips¡±µÄÖµÊÇ·ñ¼´ÊÇ¡°block¡±¡£ÈôÊÇÊÇ£¬·µ»Ø403 ForbiddenµÄÏìÓ¦¡£
ÉÏÊö´úÂëÖ»ÊÇÒ»¸öʾÀý£¬½öÓÃÓÚÑÝʾÔõÑùÔÚNginxÖÐʵÏÖ»ùÓÚÇëÇóȪԴIPµÄ»á¼û¿ØÖÆÉèÖá£Çëƾ֤ÏÖʵÐèÇó¾ÙÐÐÊʵ±µÄÉèÖã¬ÀýÈçÌí¼ÓÐèÒªÆÁÕϵÄIPµØµã£¬Ð޸ļàÌýµÄ¶Ë¿ÚºÅºÍÓòÃûµÈ¡£
×ܽáÀ´Ëµ£¬Nginxͨ¹ýʹÓÃmapºÍ±äÁ¿µÄ·½·¨£¬¿ÉÒÔÇáËÉʵÏÖ»ùÓÚÇëÇóȪԴIPµÄ»á¼û¿ØÖÆ¡£Í¨¹ýÔÚÉèÖÃÎļþÖоÙÐÐÏìÓ¦µÄÉèÖã¬ÎÒÃÇ¿ÉÒÔÏÞÖÆÌض¨IPµØµãµÄ»á¼ûȨÏÞ£¬´Ó¶øÌá¸ßЧÀÍÆ÷µÄÇå¾²ÐÔ¡£
ÒÔÉϾÍÊÇNginxÔõÑùʵÏÖ»ùÓÚÇëÇóȪԴIPµÄ»á¼û¿ØÖÆÉèÖõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡