NginxÔõÑùʵÏÖ»ùÓÚÇëÇó²ÎÊýµÄÇëÇóÖØдÉèÖÃ
NginxÔõÑùʵÏÖ»ùÓÚÇëÇó²ÎÊýµÄÇëÇóÖØдÉèÖÃ
Nginx×÷Ϊһ¸ö¸ßÐÔÄܵÄWebЧÀÍÆ÷ºÍ·´ÏòÊðÀíЧÀÍÆ÷£¬¾ßÓÐÇ¿Ê¢µÄÉèÖù¦Ð§¡£ÆäÖУ¬ÇëÇóÖØд¹¦Ð§ÊÇNginxÖÐÒ»¸öºÜÊÇÖ÷ÒªµÄ¹¦Ð§Ö®Ò»¡£Í¨¹ýÇëÇóÖØд£¬ÎÒÃÇ¿ÉÒÔ¶Ô¿Í»§¶ËÇëÇóÖеÄURI¾ÙÐÐÐ޸ģ¬ÊµÏÖURLÖض¨Ïò¡¢ÇëÇó²ÎÊý´¦ÀíµÈ¹¦Ð§¡£¶ø»ùÓÚÇëÇó²ÎÊýµÄÇëÇóÖØдÉèÖ㬿ÉÒÔƾ֤²î±ðµÄÇëÇó²ÎÊýÀ´¾ÙÐвî±ðµÄURLÖØд£¬´Ó¶øʵÏÖÔ½·¢ÎÞаµÄÇëÇó´¦Àí¡£
ÏÂÃæÎÒÃǽ«ÏêϸÏÈÈÝÔõÑùÔÚNginxÖÐʵÏÖ»ùÓÚÇëÇó²ÎÊýµÄÇëÇóÖØдÉèÖá£
Ò»¡¢ÉèÖÃÉÏÏÂÎÄ
ÔÚNginxÖУ¬¿ÉÒÔͨ¹ýÔÚ²î±ðµÄÉèÖÃÉÏÏÂÎÄÖоÙÐÐÇëÇóÖØдµÄÉèÖᣳ£¼ûµÄÉèÖÃÉÏÏÂÎÄ°üÀ¨server¡¢locationµÈ¡£ÔÚʵÏÖ»ùÓÚÇëÇó²ÎÊýµÄÇëÇóÖØдʱ£¬ÎÒÃÇͨ³£»áÔÚlocationÉèÖÿéÖоÙÐÐÉèÖá£
ÒÔÏÂÊÇÒ»¸ö»ù±¾µÄNginxÉèÖÃÎļþ£º
server { listen 80; server_name example.com; location / { # ÕâÀï¾ÙÐÐÇëÇóÖØдµÄÉèÖà } }
µÇ¼ºó¸´ÖÆ
¶þ¡¢»ùÓÚÇëÇó²ÎÊýµÄÇëÇóÖØдÉèÖÃ
ÔÚNginxÖУ¬¿ÉÒÔʹÓÃifÖ¸ÁîºÍrewriteÖ¸ÁîÀ´ÊµÏÖ»ùÓÚÇëÇó²ÎÊýµÄÇëÇóÖØдÉèÖá£ÏÂÃæÊÇÒ»¸öʾÀý£¬ÎÒÃǽ«Æ¾Ö¤ÇëÇó²ÎÊýidµÄÖµÀ´¾ÙÐвî±ðµÄURLÖØд£º
location / { if ($arg_id = 1) { # ÈôÊÇÇëÇó²ÎÊýidµÄֵΪ1 rewrite ^/article/(.*)$ /article-1/$1 last; # ½« /article/xxx ÖØдΪ /article-1/xxx } if ($arg_id = 2) { # ÈôÊÇÇëÇó²ÎÊýidµÄֵΪ2 rewrite ^/article/(.*)$ /article-2/$1 last; # ½« /article/xxx ÖØдΪ /article-2/xxx } # ÆäËûÇéÐÎ... }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄÉèÖÃÖУ¬ÎÒÃÇͨ¹ýifÖ¸Áî¶ÔÇëÇó²ÎÊýidµÄÖµ¾ÙÐÐÅжϣ¬ÈôÊÇÖª×ãÌõ¼þ£¬ÔòʹÓÃrewriteÖ¸Áî¶ÔURI¾ÙÐÐÖØд¡£
Èý¡¢Ê¹ÓÃMapÄ£¿é¾ÙÐÐÇëÇóÖØдÉèÖÃ
³ýÁËʹÓÃifÖ¸ÁîºÍrewriteÖ¸Á»¹¿ÉÒÔʹÓÃNginxµÄmapÄ£¿éÀ´ÊµÏÖ»ùÓÚÇëÇó²ÎÊýµÄÇëÇóÖØдÉèÖá£mapÄ£¿é¿ÉÒÔ½ç˵һ¸ö±äÁ¿Ó³Éä±í£¬Æ¾Ö¤ÇëÇó²ÎÊýµÄÖµÀ´Ó³Éä¶ÔÓ¦µÄÖØд¹æÔò¡£ÒÔÏÂÊÇÒ»¸öʹÓÃmapÄ£¿éµÄʾÀý£º
map $arg_id $id_mapping { 1 /article-1/; 2 /article-2/; default /article/; } location / { rewrite ^/article/(.*)$ $id_mapping$1 last; # ƾ֤ÇëÇó²ÎÊýidµÄÖµ¾ÙÐÐÖض¨Ïò }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄÉèÖÃÖУ¬ÎÒÃÇʹÓÃmapÄ£¿é½ç˵ÁËÒ»¸ö±äÁ¿Ó³Éä±í$id_mapping£¬Æ¾Ö¤ÇëÇó²ÎÊýidµÄÖµÀ´Ó³Éä²î±ðµÄÖØд¹æÔò¡£È»ºóÔÚlocationÉèÖÿéÖÐʹÓÃrewriteÖ¸Áî¾ÙÐÐÇëÇóÖØд£¬Æ¾Ö¤Ó³Éä±íµÄÖµÀ´ÖØдURI¡£
ËÄ¡¢×¢ÖØÊÂÏî
ÔÚʵÏÖ»ùÓÚÇëÇó²ÎÊýµÄÇëÇóÖØдÉèÖÃʱ£¬ÐèҪעÖØÒÔϼ¸µã£º
Ö»¹Ü×èÖ¹¹ý¶àµÄifÖ¸Á¹ý¶àµÄifÖ¸Áî»á¶ÔÐÔÄܱ¬·¢Ò»¶¨µÄÓ°Ï죻
ʹÓÃmapÄ£¿éÄܹ»Ô½·¢ÇåÎúµØ½ç˵±äÁ¿Ó³Éä±í£¬ÔöÇ¿ÁËÉèÖõĿɶÁÐԺͿÉά»¤ÐÔ£»
µ±ÉèÖýÏΪÖØ´óʱ£¬½¨ÒéÏȾÙÐмòÆӵIJâÊÔ£¬È·±£ÇëÇó²ÎÊýµÄÖµÄܹ»×¼È·´¥·¢ÏìÓ¦µÄÇëÇóÖØд¹æÔò¡£
½áÓï
ͨ¹ý±¾ÎĵÄÏÈÈÝ£¬ÎÒÃÇÏàʶÁËÔõÑùÔÚNginxÖÐʵÏÖ»ùÓÚÇëÇó²ÎÊýµÄÇëÇóÖØдÉèÖá£ÎÞÂÛÊÇʹÓÃifÖ¸ÁîºÍrewriteÖ¸ÁÕÕ¾ÉʹÓÃmapÄ£¿é£¬¶¼Äܹ»ÊµÏÖÎÞаµÄÇëÇóÖØд¹¦Ð§¡£Í¬Ê±£¬ÔÚÉèÖÃʱÐèҪעÖØÐÔÄܺͿÉά»¤ÐÔ£¬×èֹ̫¹ýÖØ´óµÄÉèÖã¬ÒÔ°ü¹ÜЧÀÍÆ÷µÄÎȹÌÐÔºÍÐÔÄÜ¡£
Ï£Íû±¾ÎÄÄܹ»¶Ô¸÷ÈËÃ÷È·NginxµÄÇëÇóÖØд¹¦Ð§ÓÐËù×ÊÖú£¬Í¬Ê±¶ÔÉèÖÃNginxʱԽ·¢ÎÞаµØ´¦ÀíÇëÇó²ÎÊýÓÐËùÆô·¢¡£
ÒÔÉϾÍÊÇNginxÔõÑùʵÏÖ»ùÓÚÇëÇó²ÎÊýµÄÇëÇóÖØдÉèÖõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡