Nginx·´ÏòÊðÀíÉèÖÃÓòÃû£¬ÓÅÑÅʵÏÖת·¢
nginx·´ÏòÊðÀíÉèÖÃÓòÃû£¬ÓÅÑÅʵÏÖת·¢
¸ÅÊö
ÔÚWeb¿ª·¢ÖУ¬¾³£»áÓöµ½ÐèÒªÊðÀíת·¢ÇëÇóµÄÇéÐΡ£Nginx×÷Ϊһ¿î¸ßÐÔÄܵÄWebЧÀÍÆ÷£¬¿ÉÒÔͨ¹ý·´ÏòÊðÀíÀ´ÊµÏÖÇëÇóµÄת·¢£¬´Ó¶øʵÏÖ¸ßЧµÄ¸ºÔØƽºâºÍ¶¯Ì¬ÉèÖá£
Nginx·´ÏòÊðÀíµÄ»ùÀ´Ô´ÀíÊǽ«ÇëÇó´Ó¿Í»§¶Ë·¢Ë͵½NginxЧÀÍÆ÷£¬NginxЧÀÍÆ÷ÔÙ¾ÙÐÐת·¢£¬½«ÇëÇó·¢Ë͵½ÕæÕý´¦ÀíÇëÇóµÄºó¶ËЧÀÍÆ÷ÉÏ¡£Í¨¹ýÉèÖÃÓòÃû£¬ÎÒÃÇ¿ÉÒÔʵÏÖ¶Ô²î±ðÓòÃûµÄÇëÇó¾ÙÐвî±ðµÄÊðÀíת·¢¹æÔò¡£
ÉèÖÃÓòÃû
ҪʵÏÖ¶ÔÓòÃûµÄÊðÀíת·¢£¬Ê×ÏÈÐèÒªÉèÖúÃÓòÃûµÄÆÊÎö¡£¼ÙÉèÎÒÃÇÓÐÁ½¸öÓòÃûÐèҪת·¢£¬»®·ÖÊÇwww.example1.comºÍwww.example2.com£¬ÎÒÃÇ¿ÉÒÔÔÚDNSЧÀÍÉ̵ĿØÖÆ̨ÉϽ«ÕâÁ½¸öÓòÃûÆÊÎöµ½NginxЧÀÍÆ÷µÄIPµØµãÉÏ¡£
½ÓÏÂÀ´£¬ÎÒÃÇÐèÒªÔÚNginxµÄÉèÖÃÎļþÖÐÉèÖÃÓòÃûµÄÊðÀíת·¢¹æÔò¡£·¿ªNginxµÄÉèÖÃÎļþ£¬Ò»Ñùƽ³£Î»ÓÚ/etc/nginx/nginx.conf£¬ÕÒµ½server¿é£¬È»ºóÔÚserver¿éÄÚÉèÖÃÏìÓ¦µÄÓòÃûºÍת·¢¹æÔò¡£
ʾÀý´úÂëÈçÏ£º
server { listen 80; server_name www.example1.com; location / { proxy_pass http://backend1; proxy_set_header Host $host; } } server { listen 80; server_name www.example2.com; location / { proxy_pass http://backend2; proxy_set_header Host $host; } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬ÎÒÃÇÊ×ÏȽç˵ÁËÒ»¸öserver¿é£¬ÉèÖÃÁËlistenÖ¸Áî¼àÌý80¶Ë¿Ú£¬server_nameÖ¸ÁîÉèÖÃÁËÓòÃûΪwww.example1.com¡£location¿éÄÚµÄÉèÖÃÖ¸Áîproxy_passÔòÖ¸¶¨ÁËÇëÇóµÄת·¢Ä¿µÄΪhttp://backend1¡£proxy_set_headerÖ¸ÁîÉèÖÃÁËÇëÇóÍ·µÄHost×Ö¶ÎΪ$host£¬ÕâÊÇΪÁ˼á³ÖÇëÇóµÄÕæʵÐÔ¡£
ÀàËƵأ¬ÎÒÃÇÔÙÌí¼ÓÒ»¸öserver¿é£¬ÉèÖÃserver_nameΪwww.example2.com£¬proxy_passΪhttp://backend2¡£
ÉèÖÃת·¢Ä¿µÄ
ÔÚÉÏÃæµÄÉèÖÃÖУ¬ÎÒÃÇʹÓÃÁËbackend1ºÍbackend2×÷Ϊת·¢µÄÄ¿µÄ¡£ÕâÁ½¸öÄ¿µÄÖ¸µÄÊǺó¶ËЧÀÍÆ÷µÄµØµã£¬¿ÉÒÔÊÇÓòÃû¡¢IPµØµã»òUNIX domain socket¡£
Òª½«ÕâÁ½¸öת·¢Ä¿µÄÓëÏÖʵ´¦ÀíÇëÇóµÄºó¶ËЧÀÍÆ÷¹ØÁªÆðÀ´£¬ÎÒÃÇÐèÒªÔÚNginxµÄÉèÖÃÎļþµÄhttp¿éÄÚÌí¼ÓÒ»¸öupstream¿é£¬Ê¾Àý´úÂëÈçÏ£º
http { upstream backend1 { server backend1.example.com; } upstream backend2 { server backend2.example.com; } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬ÎÒÃǽç˵ÁËÁ½¸öupstream¿é£¬Í¨¹ýserverÖ¸Áºó¶ËЧÀÍÆ÷µÄµØµãÓëbackend1ºÍbackend2¹ØÁªÆðÀ´¡£ÆäÖУ¬backend1.example.comºÍbackend2.example.comÊÇÏÖʵ´¦ÀíÇëÇóµÄºó¶ËЧÀÍÆ÷µÄµØµã¡£
ÖØÆôNginx
Íê³ÉÓòÃûºÍת·¢Ä¿µÄµÄÉèÖúó£¬ÎÒÃÇÐèÒªÖØÆôNginxЧÀÍÆ÷£¬Ê¹ÉèÖÃÉúЧ¡£ÔÚÖÕ¶ËÖÐÊäÈëÒÔÏÂÏÂÁî¾ÙÐÐÖØÆô£º
sudo service nginx restart
µÇ¼ºó¸´ÖÆ
È»ºó£¬¾Í¿ÉÒÔͨ¹ý»á¼ûwww.example1.comºÍwww.example2.comÀ´²âÊÔת·¢ÊÇ·ñ׼ȷÉèÖá£
×ܽá
ͨ¹ýÉèÖÃÓòÃûºÍת·¢¹æÔò£¬ÎÒÃÇ¿ÉÒÔʵÏÖNginxµÄ·´ÏòÊðÀí£¬½«ÇëÇóת·¢µ½²î±ðµÄºó¶ËЧÀÍÆ÷ÉÏ¡£ÕâÑù¿ÉÒÔÎÞаµØÉèÖÃת·¢¹æÔò£¬ÊµÏÖ¸ßЧµÄ¸ºÔØƽºâºÍ¶¯Ì¬ÉèÖá£Í¬Ê±£¬Nginx»¹ÌṩÁ˸»ºñµÄÄ£¿éºÍ¹¦Ð§£¬¿ÉÒÔ½øÒ»²½À©Õ¹·´ÏòÊðÀíµÄÄÜÁ¦£¬Öª×ã¸ü¶àµÄÐèÇó¡£
ÒÔÉϾÍÊÇNginx·´ÏòÊðÀíÉèÖÃÓòÃû£¬ÓÅÑÅʵÏÖת·¢µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡