NginxÔõÑùʵÏÖ»ùÓÚÏìӦͷµÄÇëÇóÖض¨ÏòÉèÖÃ
NginxÔõÑùʵÏÖ»ùÓÚÏìӦͷµÄÇëÇóÖض¨ÏòÉèÖÃ
NginxÊÇÒ»¿î×ÔÓÉ¿ªÔ´µÄ¸ßÐÔÄÜWebЧÀÍÆ÷£¬Ò²ÊÇÏÖÔÚ»¥ÁªÍøÇ°¶Ë¿ª·¢ÖкÜÊÇÆÕ±éʹÓõķ´ÏòÊðÀíЧÀÍÆ÷¡£ÔÚNginxÖУ¬ÎÒÃÇ¿ÉÒÔͨ¹ýÉèÖÃÎļþÀ´ÊµÏÖÖÖÖÖ¹¦Ð§£¬°üÀ¨»ùÓÚÏìӦͷµÄÇëÇóÖض¨Ïò¡£
ÇëÇóÖض¨ÏòÊÇÖ¸ÔÚЧÀÍÆ÷¶ËÏò¿Í»§¶Ë·µ»ØÒ»¸öÌض¨µÄÏìӦͷ£¬¸æËß¿Í»§¶Ë½«Ä¿½ñÇëÇóÖض¨Ïòµ½Ò»¸öеÄURL¡£»ùÓÚÏìӦͷµÄÇëÇóÖض¨Ïò¿ÉÒÔʵÏÖÐí¶à¹¦Ð§£¬ºÃ±Èƾ֤Óû§Éí·Ý¡¢×°±¸ÀàÐÍ»ò»á¿´·¨ÓòµÈÐÅÏ¢À´¶¯Ì¬µØµ÷½âÒ³ÃæÌøת¡£
ҪʵÏÖ»ùÓÚÏìӦͷµÄÇëÇóÖض¨ÏòÉèÖã¬Ê×ÏÈÐèÒª±à¼NginxµÄÉèÖÃÎļþ¡£Ò»Ñùƽ³£ÇéÐÎÏ£¬NginxµÄÉèÖÃÎļþλÓÚ/etc/nginx/nginx.conf»ò/usr/local/nginx/conf/nginx.conf¡£ÔÚÕâ¸öÉèÖÃÎļþÖУ¬ÎÒÃÇÐèÒªÌí¼ÓÒÔÏ´úÂëʾÀýÀ´ÉèÖÃÇëÇóÖض¨Ïò£º
server { listen 80; server_name example.com; location / { if ($http_user_agent ~* "Android" ) { return 301 http://m.example.com$request_uri; } if ($http_user_agent ~* "iPhone" ) { return 301 http://m.example.com$request_uri; } return 200 'Hello, world!'; } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëʾÀýÖУ¬ÎÒÃǽç˵ÁËÒ»¸öserver¿é£¬¼àÌý80¶Ë¿Ú£¬²¢ÉèÖÃÁËЧÀÍÆ÷Ãû³ÆΪexample.com¡£ÔÚlocation¿éÖУ¬ÎÒÃÇʹÓÃifÓï¾äÀ´Æ¾Ö¤ÇëÇóµÄUser-AgentÍ·ÐÅÏ¢ÅжϿͻ§¶Ë×°±¸ÀàÐÍ¡£ÈôÊÇÊÇAndroid×°±¸»òiPhone×°±¸£¬¾Í»á½«ÇëÇóÖض¨Ïòµ½m.example.com¡£ÈôÊDz»Öª×ãÕâÁ½¸öÌõ¼þ£¬¾Í»á·µ»ØÒ»¸ö200µÄÏìÓ¦£¬ÏÔʾ’Hello, world!’µÄÐÂÎÅ¡£
ÐèҪעÖصÄÊÇ£¬ifÓï¾äÊÇÒ»ÖÖÇáÓ¯µÄÉèÖ÷½·¨£¬µ«Ëü²»ÊÇNginxµÄ×î¼Ñʵ¼ù¡£ÔÚÉú²úÇéÐÎÖУ¬×îºÃʹÓÃNginxµÄrewriteÄ£¿éÀ´ÊµÏÖÇëÇóÖض¨Ïò£¬ÓÉÓÚrewriteÄ£¿é¿ÉÒÔ¸ü¸ßЧµØ´¦ÀíÇëÇ󣬲¢ÇÒ¾ßÓиüÎÞаµÄÉèÖÃÑ¡Ïî¡£ÏÂÃæÊÇʹÓÃrewriteÄ£¿éµÄ´úÂëʾÀý£º
server { listen 80; server_name example.com; location / { if ($http_user_agent ~* "Android" ) { rewrite ^ http://m.example.com$request_uri permanent; } if ($http_user_agent ~* "iPhone" ) { rewrite ^ http://m.example.com$request_uri permanent; } return 200 'Hello, world!'; } }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸ö´úÂëʾÀýÖУ¬ÎÒÃÇʹÓÃrewriteÖ¸ÁîÀ´ÊµÏÖÇëÇóÖض¨Ïò¡£ÓëifÓï¾ä²î±ðµÄÊÇ£¬rewriteÖ¸ÁîÄܹ»¸ü¸ßЧµØ´¦ÀíÇëÇ󣬲¢ÇÒ¿ÉÒÔ´øÉÏpermanent²ÎÊý£¬¸æËß¿Í»§¶Ë¸ÃÖض¨ÏòÊÇÓÀÊÀÐԵġ£
ÎÞÂÛÄãÑ¡ÔñʹÓÃifÓï¾äÕÕ¾ÉrewriteÖ¸Á¶¼¿ÉÒÔƾ֤ÏÖʵÐèÇóÀ´ÉèÖûùÓÚÏìӦͷµÄÇëÇóÖض¨Ïò¡£Í¨¹ýÕâÖÖ·½·¨£¬Äã¿ÉÒÔƾ֤ÇëÇóÍ·ÖеÄÐÅÏ¢¶¯Ì¬µØ½«Óû§Ìøתµ½²î±ðµÄÒ³Ã棬Ìṩ¸üºÃµÄÓû§ÌåÑé¡£
×ÛÉÏËùÊö£¬Nginx¿ÉÒÔͨ¹ýÉèÖÃÎļþÀ´ÊµÏÖ»ùÓÚÏìӦͷµÄÇëÇóÖض¨Ïò¡£ÎÞÂÛÊÇʹÓÃifÓï¾äÕÕ¾ÉrewriteÖ¸Á¶¼¿ÉÒÔƾ֤ÏÖʵÐèÇóÀ´ÉèÖÃÖض¨Ïò¹æÔò¡£Í¨¹ýºÏÀíµØÉèÖ㬿ÉÒÔʵÏÖƾ֤Óû§Éí·Ý¡¢×°±¸ÀàÐÍ»ò»á¿´·¨ÓòµÈÐÅÏ¢À´¶¯Ì¬µØµ÷½âÒ³ÃæÌøת£¬Ìṩ¸üºÃµÄÓû§ÌåÑé¡£
ÒÔÉϾÍÊÇNginxÔõÑùʵÏÖ»ùÓÚÏìӦͷµÄÇëÇóÖض¨ÏòÉèÖõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡