NginxÖض¨ÏòÉèÖÃÆÊÎö£¬ÊµÏÖURLת·¢ºÍץȡ
nginxÖض¨ÏòÉèÖÃÆÊÎö£¬ÊµÏÖurlת·¢ºÍץȡ
СÐò£º
ÔÚWebÓ¦Óÿª·¢ÖУ¬¾³£»áÓöµ½ÐèÒª¶ÔURL¾ÙÐÐÖض¨ÏòµÄÇéÐΡ£Nginx×÷ΪһÖÖ¸ßÐÔÄܵÄWebЧÀÍÆ÷ºÍ·´ÏòÊðÀíЧÀÍÆ÷£¬ÌṩÁËÇ¿Ê¢µÄÖض¨Ïò¹¦Ð§¡£±¾ÎĽ«¶ÔNginxµÄÖض¨ÏòÉèÖþÙÐÐÆÊÎö£¬²¢Í¨¹ý´úÂëʾÀýչʾÔõÑùʵÏÖURLת·¢ºÍץȡµÄ¹¦Ð§¡£
Ò»¡¢»ù±¾¿´·¨
Öض¨ÏòÊÇÖ¸½«Ò»¸öURLÇëÇóת·¢µ½ÁíÒ»¸öURLµÄÀú³Ì¡£ÔÚNginxÖУ¬¿ÉÒÔͨ¹ýÉèÖÃÎļþÀ´ÊµÏÖÖض¨Ïò¹¦Ð§¡£NginxµÄÖض¨ÏòÉèÖÃÖ÷ÒªÉæ¼°Á½¸öÖ¸ÁrewriteºÍreturn¡£
rewriteÖ¸ÁÓÃÓÚ½«ÇëÇóµÄURLƾָ֤¶¨¹æÔò¾ÙÐÐÖØд¡£³£¼ûµÄÓ÷¨ÓУº
rewrite ^/old-url$ /new-url permanent;£º½«ÒÔ/old-url¿ªÍ·µÄÇëÇóÖض¨Ïòµ½/new-url¡£
rewrite ^/(.*)$ /index.php?page=$1 last;£º½«ÇëÇóת·¢µ½index.php£¬²¢½«ÇëÇóµÄURL×÷Ϊ²ÎÊýת´ï¸øpage²ÎÊý¡£
returnÖ¸ÁÓÃÓÚƾ֤ÇëÇóµÄ״̬Âë¾ÙÐÐÖض¨Ïò¡£³£¼ûµÄÓ÷¨ÓУº
return 301 http://www.example.com/new-url;£ºÓÀÊÀÖض¨Ïòµ½http://www.example.com/new-url¡£
return 302 /new-url;£ºÔÝʱÖض¨Ïòµ½/new-url¡£
¶þ¡¢URLת·¢Ê¾Àý
URLת·¢ÊÇÒ»ÖÖÖض¨Ïò·½·¨£¬¿ÉÒÔ½«ÇëÇóת·¢µ½ÁíÒ»¸öURLÒÔʵÏÖ²î±ðµÄ¹¦Ð§¡£ÏÂÃæͨ¹ýÒ»¸öʵÀýÀ´Õ¹Ê¾ÔõÑùÔÚNginxÖÐʵÏÖURLת·¢¡£
¼ÙÉèÎÒÃÇÓÐÒ»¸öWebÓ¦Óã¬Óû§»á¼ûhttp://www.example.com/searchʱ£¬ÎÒÃÇÏ£Íû½«ÇëÇóת·¢µ½http://www.example.com/search.phpÀ´Ö´ÐÐËÑË÷¹¦Ð§¡£ÎÒÃÇ¿ÉÒÔÔÚNginxµÄÉèÖÃÎļþÖÐÌí¼ÓÈçÏÂÉèÖãº
location ^~ /search { rewrite ^/search$ /search.php break; }
µÇ¼ºó¸´ÖÆ
Ú¹ÊÍ£º
location ^~ /searchÖ¸¶¨ÁËÒ»¸öÒÔ/search¿ªÍ·µÄÇëÇóλÖá£
rewrite ^/search$ /search.php break;½«ÒÔ/search¿ªÍ·µÄÇëÇóÖØдΪ/search.php£¬Í¬Ê±Ê¹ÓÃbreakÒªº¦×Ö×èÖ¹ÖØдÀú³Ì¡£
Èý¡¢URLץȡʾÀý
URLץȡÊÇÒ»ÖÖÖض¨Ïò·½·¨£¬¿ÉÒÔ½«ÇëÇóת·¢µ½ÁíÒ»¸öURL£¬²¢»ñÈ¡¸ÃURL·µ»ØµÄÄÚÈÝ¡£ÏÂÃæͨ¹ýÒ»¸öʵÀýÀ´Õ¹Ê¾ÔõÑùÔÚNginxÖÐʵÏÖURLץȡ¡£
¼ÙÉèÎÒÃÇÓÐÒ»¸öWebÓ¦Óã¬Óû§»á¼ûhttp://www.example.com/static/1.jpgʱ£¬ÎÒÃÇÏ£Íû½«ÇëÇóת·¢µ½http://www.example.com/images/1.jpg£¬²¢»ñÈ¡¸ÃͼƬµÄÄÚÈÝ¡£ÎÒÃÇ¿ÉÒÔÔÚNginxµÄÉèÖÃÎļþÖÐÌí¼ÓÈçÏÂÉèÖãº
location ^~ /static { proxy_pass http://www.example.com/images; }
µÇ¼ºó¸´ÖÆ
Ú¹ÊÍ£º
location ^~ /staticÖ¸¶¨ÁËÒ»¸öÒÔ/static¿ªÍ·µÄÇëÇóλÖá£
proxy_pass http://www.example.com/images;½«ÇëÇóת·¢µ½http://www.example.com/images£¬²¢»ñÈ¡¸ÃURL·µ»ØµÄÄÚÈÝ¡£
½áÂÛ£º
NginxÌṩÁËÇ¿Ê¢µÄÖض¨Ïò¹¦Ð§£¬¿ÉÒÔͨ¹ýÉèÖÃÎļþʵÏÖURLת·¢ºÍץȡ¡£±¾ÎÄͨ¹ý´úÂëʾÀýÑÝʾÁËÔõÑùÔÚNginxÖÐÉèÖÃÖض¨Ïò£¬²¢ÊµÏÖURLת·¢ºÍץȡµÄ¹¦Ð§¡£ÔÚÏÖʵӦÓÃÖУ¬Æ¾Ö¤ÐèÇóÎÞаÉèÖÃNginxµÄÖض¨Ïò¹æÔò£¬¿ÉÒÔÓÐÓÃÌáÉýWebÓ¦ÓõÄÐÔÄܺ͹¦Ð§¡£
²Î¿¼ÎÄÏ×£º
Nginx Documentation. (2021). URL Rewriting.
Nginx Documentation. (2021). Proxy Pass.
ÒÔÉÏΪ¶ÔnginxÖض¨ÏòÉèÖÃÆÊÎö£¬ÊµÏÖurlת·¢ºÍץȡµÄÎÄÕ¡£
ÒÔÉϾÍÊÇNginxÖض¨ÏòÉèÖÃÆÊÎö£¬ÊµÏÖURLת·¢ºÍץȡµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡