NginxÔõÑùʵÏÖ»ùÓÚÇëÇóURIµÄÇëÇóÖØдÉèÖÃ
NginxÔõÑùʵÏÖ»ùÓÚÇëÇóURIµÄÇëÇóÖØдÉèÖã¬ÐèÒªÏêϸ´úÂëʾÀý
Nginx×÷Ϊһ¸ö¸ßÐÔÄܵÄWebЧÀÍÆ÷ºÍ·´ÏòÊðÀíЧÀÍÆ÷£¬¾³£ÓÃÓÚ¶ÔÇëÇó¾ÙÐÐÖØдºÍת·¢¡£ÔÚÏÖʵӦÓÃÖУ¬ÎÒÃǾ³£»áÓöµ½ÐèҪƾ֤ÇëÇóµÄURI¶ÔÇëÇó¾ÙÐÐÖØдµÄÇéÐΡ£ÕâƪÎÄÕ½«ÏÈÈÝÔõÑùÔÚNginxÖÐʵÏÖ»ùÓÚÇëÇóURIµÄÇëÇóÖØдÉèÖ㬲¢ÌṩÏêϸµÄ´úÂëʾÀý¡£
NginxÖеÄÇëÇóÖØдÖ÷Ҫͨ¹ýrewriteÖ¸ÁîÀ´ÊµÏÖ¡£rewriteÖ¸ÁîµÄ»ù±¾Óï·¨ÈçÏ£º
rewrite regex replacement [flag];
µÇ¼ºó¸´ÖÆ
ÆäÖУ¬regexÌåÏÖÓÃÓÚÆ¥ÅäÇëÇóURIµÄÕýÔò±í´ïʽ£¬replacementÌåÏÖÖØдºóµÄURI£¬flagÌåÏÖÖØдµÄ±ê¼Ç¡£ÏÂÃ潫ͨ¹ýÏêϸµÄÀý×ÓÀ´ÏÈÈÝÔõÑùʹÓÃrewriteÖ¸ÁîÀ´ÊµÏÖ»ùÓÚÇëÇóURIµÄÇëÇóÖØдÉèÖá£
ʾÀýÒ»£º¼òÆÓµÄÇëÇóÖØд
¼ÙÉèÎÒÃÇÏ£Íû½«ËùÓÐÇëÇóURIÖаüÀ¨ “/old/” µÄ²¿·ÖÌ滻Ϊ “/new/”£¬ÎÒÃÇ¿ÉÒÔʹÓÃÈçϵÄNginxÉèÖãº
server { listen 80; server_name example.com; location / { rewrite /old/(.*) /new/$1 last; } }
µÇ¼ºó¸´ÖÆ
Õâ¶ÎÉèÖõÄÒâ˼ÊÇ£¬Æ¥ÅäËùÓаüÀ¨ “/old/” µÄÇëÇóURI£¬²¢½«ÆäÖÐµÄ “/old/” ²¿·ÖÌ滻Ϊ “/new/”£¬È»ºó½«ÖØдºóµÄURI¼ÌÐø½»¸øNginx´¦Àí¡£
ʾÀý¶þ£º»ùÓÚÌõ¼þµÄÇëÇóÖØд
ÓÐʱ¼äÎÒÃÇÏ£Íûƾ֤ÇëÇóURIÖеÄÏêϸÄÚÈÝÀ´È·¶¨ÖØдµÄ·½·¨¡£ºÃ±È£¬ÎÒÃÇÏëÒª½«ËùÓÐÒÔ “.html” ×îºóµÄÇëÇóURIÖØдΪÒÔ “.php” ×îºóµÄURI£¬¿ÉÒÔÕâÑùÉèÖÃNginx£º
server { listen 80; server_name example.com; location / { if ($request_uri ~* .html$) { rewrite ^(.*).html$ $1.php last; } } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄÉèÖÃÖУ¬Ê¹ÓÃÁËifÖ¸ÁîÀ´ÅжÏÇëÇóURIÊÇ·ñÒÔ “.html” ×îºó£¬ÈôÊÇÊÇ£¬Ôòͨ¹ýrewriteÖ¸ÁÆäÖØдΪÒÔ “.php” ×îºóµÄURI¡£
ʾÀýÈý£º¶àÖØÌõ¼þµÄÇëÇóÖØд
ÓÐʱ¼äÎÒÃÇÐèҪƾ֤¶àÖÖÌõ¼þ×éºÏÀ´È·¶¨ÇëÇóµÄÖØд·½·¨¡£ºÃ±È£¬ÎÒÃÇÏ£Íûƾ֤ÇëÇóURIÖеIJî±ð²¿·ÖÀ´¾öÒéÊÇ·ñ¾ÙÐÐÖØд£¬¿ÉÒÔÕâÑùÉèÖÃNginx£º
server { listen 80; server_name example.com; location / { if ($request_uri ~* /category1/) { rewrite ^/category1/(.*) /newcategory/$1 last; } if ($request_uri ~* /category2/) { rewrite ^/category2/(.*) /anothercategory/$1 last; } } }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öÉèÖÃÖУ¬Æ¾Ö¤ÇëÇóURIÖеIJî±ð²¿·Ö¾ÙÐÐÁ˶à¸öÌõ¼þÅжϣ¬È»ºóƾ֤²î±ðµÄÌõ¼þʹÓÃrewriteÖ¸Áî¾ÙÐÐÁËÏìÓ¦µÄÖØд¡£
ÐèҪעÖصÄÊÇ£¬ËäÈ»¿ÉÒÔʹÓÃifÖ¸ÁîÀ´ÊµÏÖÌõ¼þÅжϣ¬¿ÉÊÇifÖ¸Áî»á´øÀ´ÐÔÄÜÉϵÄËðʧ£¬Òò´ËÔÚÏÖʵӦÓÃÖÐÓ¦Ö»¹Ü×èֹʹÓÃifÖ¸Áî¡£
ͨ¹ýÉÏÃæµÄÀý×Ó£¬ÎÒÃÇ¿ÉÒÔ¿´µ½ÔÚNginxÖÐʵÏÖ»ùÓÚÇëÇóURIµÄÇëÇóÖØдÉèÖò¢²»ÖØ´ó£¬Ö»ÐèҪʹÓÃrewriteÖ¸ÁîºÍÕýÔò±í´ïʽ¾ÙÐÐÏà¹ØÉèÖü´¿É¡£ËäÈ»£¬ÔÚÏÖʵµÄÉú²úÇéÐÎÖУ¬ÎÒÃÇ»¹ÐèÒª×ÛºÏ˼Á¿ÐÔÄÜ¡¢Çå¾²µÈÒòÏòÀ´¾ÙÐÐÔ½·¢ÖØ´óµÄÇëÇóÖØдÉèÖá£
×ÜÖ®£¬Nginx×÷Ϊһ¿î¹¦Ð§Ç¿Ê¢µÄWebЧÀÍÆ÷ºÍ·´ÏòÊðÀíЧÀÍÆ÷£¬ÆäÇëÇóÖØд¹¦Ð§ÎªÎÒÃÇÌṩÁËÎÞаµÄÉèÖÃÑ¡Ï²¢Í¨¹ýÉÏÊöµÄÀý×Ó£¬¶ÁÕß¿ÉÒÔ¶ÔNginxµÄÇëÇóÖØд¹¦Ð§ÓÐÒ»¸öÔ½·¢ÏêϸµÄÃ÷È·¡£
Ï£Íû¶ÁÕß¿ÉÒÔƾ֤±¾ÎĵÄʾÀýºÍ˵Ã÷£¬Ô½·¢ÎÞаµØ´¦ÀíNginxÖеÄÇëÇóÖØдÉèÖã¬Ìá¸ßWebÓ¦ÓõÄÐÔÄܺÍÎÞаÐÔ¡£
ÒÔÉϾÍÊÇNginxÔõÑùʵÏÖ»ùÓÚÇëÇóURIµÄÇëÇóÖØдÉèÖõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡