NginxÔõÑùʵÏÖ»ùÓÚÇëÇóÒªÁìµÄ»á¼û¿ØÖÆÉèÖÃ
NginxÔõÑùʵÏÖ»ùÓÚÇëÇóÒªÁìµÄ»á¼û¿ØÖÆÉèÖã¬ÐèÒªÏêϸ´úÂëʾÀý
ÔÚÏÖ´úµÄÍøÂçÓ¦Óÿª·¢ÖУ¬Çå¾²ÐÔÊÇÒ»¸öºÜÊÇÖ÷ÒªµÄ˼Á¿ÒòËØ¡£ÎªÁ˱£»¤ÎÒÃǵÄÓ¦ÓÃÃâÊܶñÒâ¹¥»÷ºÍ²»·¨»á¼û£¬ÎÒÃÇÐèÒª¶Ô»á¼û¾ÙÐÐÑÏ¿áµÄ¿ØÖƺÍÏÞÖÆ¡£Nginx ÊÇÒ»¸öÆÕ±éʹÓõĸßÐÔÄÜ Web ЧÀÍÆ÷£¬ËüÌṩÁËһϵÁи»ºñµÄÉèÖÃÑ¡ÏʹÎÒÃÇ¿ÉÒÔʵÏÖÎÞаºÍÇå¾²µÄ»á¼û¿ØÖÆ¡£
ÔÚ±¾ÎÄÖУ¬ÎÒ½«ÏÈÈÝÔõÑùʹÓà Nginx ʵÏÖ»ùÓÚÇëÇóÒªÁìµÄ»á¼û¿ØÖÆÉèÖá£ÏêϸÀ´Ëµ£¬ÎÒÃǽ«Ñ§Ï°ÔõÑùÏÞÖÆijЩÇëÇóÒªÁ죨ÀýÈç POST¡¢PUT¡¢DELETE£©Ö»ÔÊÐíÌض¨µÄ¿Í»§¶Ë»òÌض¨µÄȪԴ¾ÙÐлá¼û¡£
Ê×ÏÈ£¬ÎÒÃÇÐèÒª±à¼ Nginx µÄÉèÖÃÎļþ¡£Ò»Ñùƽ³£À´Ëµ£¬Nginx µÄÉèÖÃÎļþλÓÚ /etc/nginx Ŀ¼Ï嵀 nginx.conf ÎļþÖС£ÎÒÃÇ¿ÉÒÔʹÓÃÈκÎÎı¾±à¼Æ÷·¿ª²¢±à¼¸ÃÎļþ¡£
½ÓÏÂÀ´£¬ÎÒÃÇÐèÒªÔÚÉèÖÃÎļþÖÐÌí¼ÓһЩ¹æÔòÀ´ÏÞÖÆÇëÇóÒªÁì¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏ´úÂëʾÀýÀ´Ö»ÔÊÐíÌض¨µÄ¿Í»§¶ËʹÓà POST ÇëÇóÒªÁì¡£
location /api { if ($request_method !~ ^(GET|POST)$ ) { return 405; } if ($http_user_agent !~ SomeClient ) { return 403; } # ÔÊÐíµÄÉèÖüÌÐøÖ´ÐÐ ... }
µÇ¼ºó¸´ÖÆ
ÉÏÃæµÄ´úÂëÖУ¬ÎÒÃÇÊ×ÏÈʹÓà $request_method ±äÁ¿À´¼ì²éÇëÇóÒªÁìÊÇ·ñΪ GET »ò POST¡£ÈôÊDz»ÊÇ£¬·µ»Ø HTTP ״̬Âë 405£¬ÌåÏÖ¸ÃÇëÇóÒªÁì²»±»ÔÊÐí¡£È»ºó£¬ÎÒÃÇʹÓà $http_user_agent ±äÁ¿À´¼ì²éÇëÇóµÄ¿Í»§¶ËÊÇ·ñΪ SomeClient¡£ÈôÊDz»ÊÇ£¬·µ»Ø HTTP ״̬Âë 403£¬ÌåÏָÿͻ§¶Ë²»±»ÔÊÐí¡£×îºó£¬ÎÒÃÇ¿ÉÒÔÔÚ # ÔÊÐíµÄÉèÖüÌÐøÖ´ÐÐ µÄλÖÃÌí¼ÓÔÊÐíµÄÉèÖã¬ÀýÈç´¦Àí¸ÃÇëÇóµÄºó¶ËЧÀÍÆ÷µØµãµÈ¡£
³ýÁËÉÏÃæµÄÀý×Ó£¬ÎÒÃÇ»¹¿ÉÒÔʹÓÃÆäËû±äÁ¿¡¢ÕýÔò±í´ïʽµÈ¸üÖØ´óµÄÌõ¼þÀ´ÊµÏÖ¸üϸÄåµÄ»á¼û¿ØÖÆ¡£ÒÔÏÂÊÇÒ»¸ö¸üͨÓõĴúÂëʾÀý£¬ÑÝʾÔõÑù»ùÓÚÇëÇóÒªÁìºÍȪԴ IP µØµãÀ´¿ØÖÆ»á¼û£º
geo $allowed_ips { default 0; 127.0.0.1/32 1; 192.168.0.0/24 1; } location /api { if ($request_method !~ ^(GET|POST)$ ) { return 405; } if ($allowed_ips != 1 ) { return 403; } # ÔÊÐíµÄÉèÖüÌÐøÖ´ÐÐ ... }
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂëÖУ¬ÎÒÃÇÊ×ÏȽç˵ÁËÒ»¸öÃûΪ $allowed_ips µÄµØÓßλÖñäÁ¿¡£Ä¬ÈÏÇéÐÎÏ£¬ËüµÄֵΪ 0£¬ÌåÏ־ܾøËùÓÐ IP µØµã¡£È»ºó£¬ÎÒÃÇʹÓÃÁËÁ½¸öÏêϸµÄ IP µØµã£¨127.0.0.1 ºÍ 192.168.0.0/24£©£¬½«ÆäÖµÉèÖÃΪ 1£¬ÌåÏÖÔÊÐíÕâЩ IP µØµã»á¼û¡£×îºó£¬ÎÒÃÇʹÓà $allowed_ips ±äÁ¿À´¼ì²éȪԴ IP µØµãÊÇ·ñ±»ÔÊÐí£¬²»ÔÊÐíµÄ»°·µ»Ø 403 ¹ýʧ¡£
ͨ¹ýÒÔÉϵÄʾÀý£¬ÎÒÃÇ¿ÉÒÔ¿´µ½ÔõÑùʹÓà Nginx µÄÉèÖÃÑ¡ÏîÀ´ÊµÏÖ»ùÓÚÇëÇóÒªÁìµÄ»á¼û¿ØÖÆ¡£Í¨¹ýÌí¼ÓÊʵ±µÄÌõ¼þºÍ¹æÔò£¬ÎÒÃÇ¿ÉÒÔÏÞÖƶÔÎÒÃǵÄÓ¦ÓóÌÐòµÄ²»·¨»á¼û£¬±£»¤Ãô¸ÐÊý¾ÝºÍ×ÊÔ´¡£ËäÈ»£¬ÏêϸµÄÉèÖùæÔò»áƾ֤ÏÖʵӦÓõÄÐèÇóºÍÇéÐζøÓÐËù²î±ð¡£
×ܽáÆðÀ´£¬Nginx ÌṩÁËÇ¿Ê¢µÄÉèÖÃÑ¡ÏʹÎÒÃÇÄܹ»ÊµÏÖ»ùÓÚÇëÇóÒªÁìµÄ»á¼û¿ØÖÆ¡£Í¨¹ýʹÓÃÊʵ±µÄÌõ¼þºÍ¹æÔò£¬ÎÒÃÇ¿ÉÒÔ׼ȷ¿ØÖÆ»á¼û£¬²¢±£»¤ÎÒÃǵÄÓ¦ÓóÌÐòÃâÊÜDZÔÚµÄΣº¦¡£ÔÚÏÖʵӦÓÃÖУ¬ÎÒÃÇ¿ÉÒÔƾ֤ÐèÇó½øÒ»²½¶¨ÖƺÍϸ»¯ÉèÖùæÔò£¬ÒÔÖª×ãÌض¨µÄÇå¾²ÐÔÒªÇó¡£
ÒÔÉϾÍÊÇNginxÔõÑùʵÏÖ»ùÓÚÇëÇóÒªÁìµÄ»á¼û¿ØÖÆÉèÖõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡