NginxЧÀÍÆ÷µÄÇå¾²ÉèÖúͷÀ»¤Õ½ÂÔÏê½â
nginxЧÀÍÆ÷µÄÇå¾²ÉèÖúͷÀ»¤Õ½ÂÔÏê½â
¸ÅÊö£º
Ëæ×Å»¥ÁªÍøµÄÉú³¤ºÍ´óÊý¾Ýʱ´úµÄµ½À´£¬WebЧÀÍÆ÷µÄÇå¾²ÐÔÔ½À´Ô½Êܵ½ÖØÊÓ¡£ÔÚÖÚ¶àµÄWebЧÀÍÆ÷ÖУ¬NginxÒòÆä¸ßÐÔÄÜ¡¢¸ß²¢·¢´¦ÀíÄÜÁ¦ºÍÎÞаµÄÄ£¿é»¯Éè¼ÆµÈÓŵã¶ø¹ãÊܽӴý¡£±¾ÎĽ«ÏêϸÏÈÈÝNginxЧÀÍÆ÷µÄÇå¾²ÉèÖúͷÀ»¤Õ½ÂÔ£¬°üÀ¨»á¼û¿ØÖÆ¡¢·´ÏòÊðÀí¡¢ÏÞÁ÷ºÍHTTPSÉèÖõȡ£
Ò»¡¢»á¼û¿ØÖÆ
IPºÚÃûµ¥ºÍ°×Ãûµ¥£ºÍ¨¹ýÉèÖÃNginxµÄallowºÍdenyÖ¸Á¿ÉÒÔÉèÖÃIPºÚÃûµ¥ºÍ°×Ãûµ¥¡£ÔÚNginxµÄÉèÖÃÎļþÖУ¬¿ÉÒÔʹÓÃÈçÏ´úÂëʾÀý£º
http { server { location / { deny 192.168.1.1; allow all; } } }
µÇ¼ºó¸´ÖÆ
ÉÏÊöÉèÖÃÖУ¬¾Ü¾øIPΪ192.168.1.1µÄ»á¼û£¬ÆäËûIP¿ÉÒÔÕý³£»á¼û¡£
±ÜÃâ¶ñÒâÇëÇó£ºÍ¨¹ýÉèÖÃÏÞÖÆÅþÁ¬ÊýºÍÏÞÖÆ»á¼ûƵÂÊ£¬¿ÉÒÔ±ÜÃâ¶ñÒâÇëÇóµÄ¹¥»÷¡£¿ÉÒÔÔÚNginxµÄÉèÖÃÎļþÖÐʹÓÃlimit_connºÍlimit_reqÖ¸ÁîÀ´ÊµÏÖ£¬ÈçÏÂËùʾ£º
http { server { location / { limit_conn conn_limit_per_ip 10; limit_req zone=req_limit_per_ip burst=20 nodelay; } } }
µÇ¼ºó¸´ÖÆ
ÉÏÊöÉèÖÃÖУ¬ÏÞÖÆÿ¸öIPµÄ²¢·¢ÅþÁ¬ÊýΪ10£¬ÏÞÖÆÿ¸öIPµÄÇëÇóƵÂÊΪÿÃë20¸ö¡£
¶þ¡¢·´ÏòÊðÀí
Òþ²ØÕæʵIP£ºÊ¹Ó÷´ÏòÊðÀí¿ÉÒÔÒþ²ØÕæʵIP£¬±£»¤Ð§ÀÍÆ÷µÄÇå¾²¡£¿ÉÒÔʹÓÃÈçÏÂÉèÖôúÂ룺
http { server { location / { proxy_pass http://backend; proxy_set_header X-Real-IP $remote_addr; } } upstream backend { server backend1.example.com; server backend2.example.com; } }
µÇ¼ºó¸´ÖÆ
ÉÏÊöÉèÖÃÖУ¬ÇëÇó»á±»·¢Ë͵½backend1.example.comºÍbackend2.example.com£¬Í¬Ê±½«ÔʼÇëÇóµÄÕæʵIPÉèÖõ½HTTPÍ·²¿ÖС£
¸ºÔØƽºâ£ºÍ¨¹ý·´ÏòÊðÀíºÍ¸ºÔØƽºâ£¬¿ÉÒÔ½«ÇëÇó·Ö·¢µ½¶à¸öºó¶ËЧÀÍÆ÷ÉÏ£¬Ìá¸ßϵͳµÄÐÔÄܺͿɿ¿ÐÔ¡£¿ÉÒÔʹÓÃÈçÏÂÉèÖôúÂ룺
http { upstream backend { server backend1.example.com; server backend2.example.com; } server { location / { proxy_pass http://backend; } } }
µÇ¼ºó¸´ÖÆ
ÉÏÊöÉèÖÃÖУ¬ÇëÇó»á±»Æ½ºâµØ·¢Ë͵½backend1.example.comºÍbackend2.example.comÖеÄЧÀÍÆ÷ÉÏ¡£
Èý¡¢ÏÞÁ÷
¿ØÖÆ»á¼ûËÙÂÊ£ºÍ¨¹ýÉèÖÃNginxµÄlimit_reqÖ¸Á¿ÉÒÔÏÞÖÆÿ¸öIPµÄ»á¼ûËÙÂÊ£¬×èÖ¹±»¶ñÒâÇëÇó¹¥»÷¡£¿ÉÒÔʹÓÃÈçÏÂÉèÖôúÂ룺
http { limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=10r/s; server { location / { limit_req zone=req_limit_per_ip burst=20 nodelay; } } }
µÇ¼ºó¸´ÖÆ
ÉÏÊöÉèÖÃÖУ¬Ã¿¸öIPµÄ»á¼ûËÙÂÊÏÞÖÆΪÿÃë10´Î£¬ÉèÖÃÇëÇóÍ»·¢ÊýΪ20¡£
ÏÞÖÆÎļþÉÏ´«´óС£ºÍ¨¹ýÉèÖÃNginxµÄclient_max_body_sizeÖ¸Á¿ÉÒÔÏÞÖÆÎļþÉÏ´«µÄ´óС£¬×èÖ¹ÉÏ´«´óÎļþÕ¼ÓÃЧÀÍÆ÷×ÊÔ´¡£¿ÉÒÔʹÓÃÈçÏÂÉèÖôúÂ룺
http { server { client_max_body_size 10m; ... } }
µÇ¼ºó¸´ÖÆ
ÉÏÊöÉèÖÃÖУ¬ÏÞÖÆÎļþÉÏ´«µÄ¾ÞϸΪ10MB¡£
ËÄ¡¢HTTPSÉèÖÃ
ÌìÉúSSLÖ¤Ê飺¿ÉÒÔʹÓÃLet’s EncryptµÈ¹¤¾ßÀ´ÌìÉúSSLÖ¤Ê飬ȷ±£HTTPSÅþÁ¬µÄÇå¾²ÐÔ¡£
ÉèÖÃHTTPSÅþÁ¬£º¿ÉÒÔʹÓÃÈçÏÂÉèÖôúÂ뽫HTTPÅþÁ¬×ª»»ÎªHTTPSÅþÁ¬£º
server { listen 80; server_name example.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl; server_name example.com; ssl_certificate /path/to/ssl_certificate.pem; ssl_certificate_key /path/to/ssl_certificate_key.pem; ... }
µÇ¼ºó¸´ÖÆ
ÉÏÊöÉèÖÃÖУ¬½«HTTPÅþÁ¬Öض¨Ïòµ½HTTPSÅþÁ¬£¬²¢ÉèÖÃSSLÖ¤ÊéºÍ˽Կ¡£
×ܽ᣺
±¾ÎÄÏÈÈÝÁËNginxЧÀÍÆ÷µÄÇå¾²ÉèÖúͷÀ»¤Õ½ÂÔ£¬°üÀ¨»á¼û¿ØÖÆ¡¢·´ÏòÊðÀí¡¢ÏÞÁ÷ºÍHTTPSÉèÖõȡ£Í¨¹ýºÏÀíµØÉèÖúÍʹÓÃÕâЩսÂÔ£¬¿ÉÒÔÌá¸ßЧÀÍÆ÷ºÍÍøÕ¾µÄÇå¾²ÐÔ£¬±£»¤ÏµÍ³ºÍÓû§µÄÊý¾ÝÇå¾²¡£²»¹ý£¬ÖµµÃ×¢ÖصÄÊÇ£¬²î±ðµÄÇéÐκÍÐèÇó¿ÉÄÜÐèÒªÕë¶ÔÐÔµÄÉèÖ㬿ª·¢ÕßӦƾ֤ÏÖÕæÏàÐξÙÐÐÑ¡ÔñºÍµ÷½â¡£
ÒÔÉϾÍÊÇNginxЧÀÍÆ÷µÄÇå¾²ÉèÖúͷÀ»¤Õ½ÂÔÏê½âµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡