NginxÔõÑùʵÏÖ»ùÓÚÇëÇóURLµÄÇëÇóÖØдÉèÖÃ
NginxÊÇÒ»¿îÇáÁ¿¡¢¸ßÐÔÄܵÄWebЧÀÍÆ÷£¬Ëü²»µ«Ö§³Ö·´ÏòÊðÀí¡¢¸ºÔØƽºâµÈ¸ß¼¶¹¦Ð§£¬»¹¾ß±¸Ç¿Ê¢µÄÇëÇóÖØдÄÜÁ¦¡£ÔÚÏÖʵµÄWebÓ¦ÓÃÖУ¬Ðí¶àÇéÐÎÏÂÐèÒª¶ÔÇëÇóURL¾ÙÐÐÖØд£¬ÒÔµÖ´ï¸üºÃµÄÓû§ÌåÑéºÍËÑË÷ÒýÇæÓÅ»¯Ð§¹û¡£±¾ÎĽ«ÏÈÈÝNginxÔõÑùʵÏÖ»ùÓÚÇëÇóURLµÄÇëÇóÖØдÉèÖ㬰üÀ¨ÏêϸµÄ´úÂëʾÀý¡£
ÖØдÓï·¨
ÔÚNginxÖУ¬¿ÉÒÔʹÓÃrewriteÖ¸ÁîÀ´¾ÙÐÐÇëÇóÖØд¡£Æä»ù±¾Óï·¨ÈçÏ£º
rewrite regex replacement [flag];
µÇ¼ºó¸´ÖÆ
ÆäÖУ¬regexÌåÏÖÕýÔò±í´ïʽ£¬ÓÃÓÚÆ¥ÅäÄ¿½ñÇëÇóURL£»replacementÌåÏÖÄ¿µÄURL£¬Ìæ»»ÔÀ´µÄURL£»flagÊÇ¿ÉÑ¡µÄ±ê¼Ç룬ÓÃÓÚ¿ØÖÆÖØдµÄÐÐΪ¡£
ÀýÈ磬ÏÂÃæµÄÖØд¹æÔò¿ÉÒÔ½«ÒÔ¡°/page/¡±¿ªÍ·µÄURLÖØдΪÏìÓ¦µÄ¡°/index.php?page=¡±ÐÎʽ£º
rewrite ^/page/(d+)$ /index.php?page=$1 last;
µÇ¼ºó¸´ÖÆ
Ú¹ÊÍÒ»ÏÂÉÏÊö¹æÔòµÄ¼ÄÒ壺
^/page/(d+)$£ºÌåÏÖÒÔ¡°/page/¡±¿ªÍ·£¬ºóÃæ¸úÉÏÒ»¸ö»ò¶à¸öÊý×ÖµÄURL£»
/index.php?page=$1£ºÌåÏÖ½«Æ¥Åäµ½µÄURL£¬ÖØдΪ¡°/index.php?page=¡±¼ÓÉÏÆ¥Åäµ½µÄÊý×Ö£»
last£ºÌåÏÖÖÕֹĿ½ñrewriteÖ¸Á·µ»ØÖØдºóµÄURL¡£
ÇëÇóÖØдʾÀý
½ÓÏÂÀ´£¬ÎÒÃǽ«Í¨¹ýʾÀýÀ´ÑÝʾÔõÑùʹÓÃNginxµÄÇëÇóÖØд¹¦Ð§£¬ÒÔ¼°ÔõÑùʵÏÖ»ùÓÚÇëÇóURLµÄÇëÇóÖØдÉèÖ᣼ÙÉèÎÒÃÇÓÐÒ»¸ö¼òÆÓµÄPHPÓ¦Óã¬ËüÓÐÁ½¸öÒ³Ã棺
/index.php£ºÊ×Ò³£¬ÓÃÓÚÏÔʾ×îеÄʮƪÎÄÕ£»
/article.php?id=XX£ºÎÄÕÂÏêÇéÒ³£¬ÓÃÓÚÏÔʾidΪXXµÄÎÄÕÂÏêϸÄÚÈÝ¡£
ÏÖÔÚ£¬ÎÒÃÇÏ£Íûͨ¹ýÇëÇóÖØдµÄ·½·¨£¬À´ÓÅ»¯Õâ¸öÓ¦ÓõÄURL½á¹¹£¬Ê¹ÆäÔ½·¢ÓѺúÍÓÅ»¯¡£ÏêϸÀ´Ëµ£¬ÎÒÃÇҪʵÏÖÒÔÏÂÁ½¸ö¹¦Ð§£º
½«Ê×Ò³µÄURL´Ó¡°/index.php¡±ÖØдΪ¡°/¡±£»
½«ÎÄÕÂÏêÇéÒ³µÄURL´Ó¡°/article.php?id=XX¡±ÖØдΪ¡°/article/XX¡±¡£
ÏÂÃæÊÇÍêÕûµÄNginxÉèÖÃÎļþºÍ×¢ÊÍÚ¹ÊÍ£º
# ½ç˵HTTP Server server { # ¼àÌý80¶Ë¿Ú£¬´¦ÀíËùÓÐÀ´×Ô¿Í»§¶ËµÄÇëÇó listen 80; # ¼àÌýµÄÓòÃû server_name example.com; # ÉèÖÃÊ×Ò³µÄÇëÇóÖØд¹æÔò location = / { rewrite ^/$ /index.php last; } # ÉèÖÃÎÄÕÂÏêÇéÒ³µÄÇëÇóÖØд¹æÔò location ~ /article/(d+) { rewrite ^/article/(d+)$ /article.php?id=$1 last; } # ÉèÖÃPHP FastCGIЧÀÍÆ÷ location ~ .php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } # ½ç˵ÍøÕ¾¸ùĿ¼ root /var/www/example.com; index index.php; }
µÇ¼ºó¸´ÖÆ
×¢ÊÍ˵Ã÷£º
µÚ1-10ÐУº½ç˵һ¸öHTTP Server£¬¼àÌý80¶Ë¿Ú£¬´¦ÀíÀ´×Ôexample.comµÄÇëÇó£»
µÚ12-17ÐУºÉèÖÃÇëÇóÖØд¹æÔò£¬½«¡°/¡±ÖØдΪ¡°/index.php¡±£»
µÚ19-26ÐУºÉèÖÃÇëÇóÖØд¹æÔò£¬½«¡°/article/XX¡±ÖØдΪ¡°/article.php?id=XX¡±£»
µÚ28-35ÐУºÉèÖÃPHP FastCGIЧÀÍÆ÷£¬¶ÔËùÓÐÒÔ¡°.php¡±×îºóµÄÇëÇó¾ÙÐд¦Àí£»
µÚ37-39ÐУº½ç˵ÍøÕ¾¸ùĿ¼ºÍĬÈÏÊ×Ò³¡£
ÔÚÉÏÊöµÄ´úÂëÖУ¬ÎÒÃÇʹÓÃÁËÁ½¸ölocationÖ¸ÁîÀ´»®·Ö½ç˵ÖØд¹æÔò£¬ËüÃÇ»®·ÖÆ¥Åä¶ÔÓ¦µÄURL¡£ÆäÖУ¬µÚÒ»¸ölocationÖ¸ÁîÆ¥ÅäµÄÊǸù·¾¶¡°/¡±£»µÚ¶þ¸ölocationÖ¸ÁîʹÓÃÁËÕýÔò±í´ïʽ£¬Æ¥ÅäµÄÊÇÒÔ¡°/article/¡±¿ªÍ·µÄURL¡£ÔÚÕâÁ½¸ölocationÖ¸ÁîÖУ¬ÎÒÃÇʹÓÃÁËrewriteÖ¸ÁîÀ´ÊµÏÖÇëÇóÖØд¡£
×ܽá
ͨ¹ý±¾ÎĵÄÏÈÈÝ£¬ÎÒÃÇÏàʶÁËNginxÔõÑùʵÏÖ»ùÓÚÇëÇóURLµÄÇëÇóÖØдÉèÖ㬲¢Í¨¹ýÏêϸµÄ´úÂëʾÀý¾ÙÐÐÁËÑÝʾ¡£ÔÚÏÖʵӦÓÃÖУ¬ÎÒÃÇ¿ÉÒÔƾ֤ÐèÇó£¬×Ô½ç˵²î±ðµÄÖØд¹æÔò£¬ÒÔÓÅ»¯ÍøÕ¾µÄURL½á¹¹£¬ÌáÉýÓû§ÌåÑéºÍËÑË÷ÒýÇæÓÅ»¯Ð§¹û¡£Ï£Íû±¾ÎÄÄܶԶÁÕßÓÐËù×ÊÖú¡£
ÒÔÉϾÍÊÇNginxÔõÑùʵÏÖ»ùÓÚÇëÇóURLµÄÇëÇóÖØдÉèÖõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡