ÔõÑùʹÓÃNginx¾ÙÐиßÐÔÄܵľ²Ì¬Îļþ»º´æ
ÔõÑùʹÓÃnginx¾ÙÐиßÐÔÄܵľ²Ì¬Îļþ»º´æ
NginxÊÇÒ»¿îÇáÁ¿¼¶µÄ¿ªÔ´WebЧÀÍÆ÷£¬ÒÔÆä¸ßÐÔÄܺ͸߲¢·¢ÄÜÁ¦¶øÊܵ½ÆÕ±éµÄ¹Ø×¢ºÍʹÓᣳýÁË×÷ΪWebЧÀÍÆ÷Ö®Í⣬NginxÉÐÓÐÒ»¸öÖ÷ÒªµÄ¹¦Ð§£¬¾ÍÊÇÌṩ¾²Ì¬Îļþ»º´æ¹¦Ð§£¬¿ÉÒÔ´ó·ùÓÅ»¯ÍøÕ¾µÄ»á¼ûËÙÂʺÍÐÔÄÜ¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓÃnginx¾ÙÐиßÐÔÄܵľ²Ì¬Îļþ»º´æ£¬²¢ÌṩÏìÓ¦µÄ´úÂëʾÀý¡£
ÉèÖÃNginx¾ÙÐо²Ì¬Îļþ»á¼û
ΪÁËÆôÓþ²Ì¬Îļþ»º´æ¹¦Ð§£¬Ê×ÏÈÐèÒªÉèÖÃNginxÒÔʶ±ðºÍ´¦Àí¾²Ì¬ÎļþµÄÇëÇó¡£Í¨³££¬¾²Ì¬Îļþ°üÀ¨Í¼Æ¬¡¢CSSÎļþºÍJavaScriptÎļþµÈ¡£ÏÂÃæÊÇÒ»¸ö¼òÆÓµÄNginxÉèÖÃʾÀý£º
server { listen 80; server_name example.com; root /path/to/static/files; location ~* .(jpg|jpeg|png|gif|css|js)$ { expires 30d; access_log off; } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöÉèÖÃÖУ¬listenÖ¸¶¨ÁËNginx¼àÌýµÄ¶Ë¿Ú£¬server_nameÖ¸¶¨ÁËЧÀÍÆ÷µÄÓòÃû¡£rootÖ¸¶¨Á˾²Ì¬ÎļþËùÔڵĸùĿ¼¡£locationÖ¸ÁîÖ¸¶¨ÁËÆ¥ÅäµÄURLģʽ£¬ÒÔ¼°¶ÔÓ¦µÄ´¦Àí²ÎÊý¡£ÔÚÉÏÃæµÄÉèÖÃÖУ¬Í¨¹ýÕýÔò±í´ïʽ~* .(jpg|jpeg|png|gif|css|js)$Æ¥ÅäÁËÒÔjpg¡¢jpeg¡¢png¡¢gif¡¢css»òjsΪºó׺µÄÎļþ£¬expiresÖ¸¶¨ÁË»º´æµÄÓÐÓÃÆÚΪ30Ì죬access_log offÔòեȡÁ˶Ծ²Ì¬ÎļþµÄ»á¼ûÈÕÖ¾¼Í¼¡£
ÉèÖÃNginx¾ÙÐо²Ì¬Îļþ»º´æ
ΪÁËÆôÓÃNginxµÄ¾²Ì¬Îļþ»º´æ¹¦Ð§£¬ÎÒÃÇ¿ÉÒÔÌí¼ÓһЩÌØÁíÍâÉèÖÃÖ¸Áî¡£ÏÂÃæÊÇÒ»¸öʾÀý£º
location ~* .(jpg|jpeg|png|gif|css|js)$ { expires 30d; access_log off; add_header Cache-Control "public"; add_header Pragma public; etag off; }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöʾÀýÖУ¬add_headerÖ¸ÁîÌí¼ÓÁËÁ½¸öÍ·²¿ÐÅÏ¢£¬»®·ÖÊÇCache-ControlºÍPragma¡£ÕâÁ½¸öÍ·²¿ÐÅÏ¢¸æËß¿Í»§¶ËºÍÆäËû»º´æЧÀÍÆ÷ÔÚһ׼ʱ¼äÄÚ¿ÉÒÔʹÓûº´æµÄ¸±±¾¡£etag off½ûÓÃÁËEtagÍ·²¿ÐÅÏ¢£¬ÓÉÓÚÔÚijЩÇéÐÎÏ£¬Etag¿ÉÄܻᵼÖÂһЩ¼æÈÝÐÔÎÊÌâ¡£
ÑéÖ¤¾²Ì¬Îļþ»º´æÊÇ·ñÉúЧ
ΪÁËÑéÖ¤¾²Ì¬Îļþ»º´æÊÇ·ñÉúЧ£¬¿ÉÒÔʹÓÃä¯ÀÀÆ÷µÄ¿ª·¢Õß¹¤¾ß»òÕßÏÂÁîÐй¤¾ß¾ÙÐÐÉó²é¡£ÔÚä¯ÀÀÆ÷µÄ¿ª·¢Õß¹¤¾ßÖУ¬¿ÉÒÔÉó²éHTTPÏìӦͷ²¿µÄCache-ControlºÍExpires×ֶΣ¬ÒÔ¼°ÏìÓ¦ÄÚÈݵľÞϸ¡£ÈôÊÇ»º´æÉúЧ£¬ÄÇôÔÚµÚÒ»´Î»á¼û¾²Ì¬Îļþºó£¬ÔÙ´ÎÇëÇóʱ»á¿´µ½Cache-ControlºÍExpiresµÄÖµÓëÉÏÊöÉèÖÃÒ»Ö£¬²¢ÇÒÏìÓ¦ÄÚÈݵľÞϸ»á±äµÃºÜÊÇС¡£
ÁíÍ⣬¿ÉÒÔʹÓÃÏÂÁîÐй¤¾ßÈçcurlÀ´Éó²éHTTPÏìӦͷ²¿ÐÅÏ¢¡£ÀýÈ磬¿ÉÒÔÖ´ÐÐÒÔÏÂÏÂÁîÀ´Éó²éÒ»¸öͼƬÎļþµÄHTTPÏìӦͷ²¿ÐÅÏ¢£º
$ curl -I example.com/path/to/image.jpg
µÇ¼ºó¸´ÖÆ
ÈôÊÇ»º´æÉúЧ£¬ÄÇôÄã»áÔÚЧ¹ûÖп´µ½ÀàËÆÏÂÃæµÄÐУº
Cache-Control: public, max-age=2592000 Expires: Thu, 10 Aug 2023 08:16:50 GMT
µÇ¼ºó¸´ÖÆ
¶¯Ì¬¸üлº´æ
ÓÐʱ¼äÎÒÃÇ¿ÉÄÜÐèÒª¶¯Ì¬µØ¸üлº´æ£¬ÀýÈçµ±¾²Ì¬Îļþ±»Ð޸ĺ󡣿ÉÒÔͨ¹ýÔÚÎļþÃû»òÕß·¾¶ÖÐÌí¼Ó°æ±¾ºÅÀ´½â¾öÕâ¸öÎÊÌâ¡£ÀýÈ磬¼ÙÉèÓÐÒ»¸öCSSÎļþstyle.css£¬ÎÒÃÇ¿ÉÒÔ½«ÆäÖØÃüÃûΪstyle.v1.css£¬²¢¸üÐÂNginxµÄÉèÖÃÎļþÒÔÆ¥ÅäеÄÎļþÃû¡£ÕâÑùÒ»À´£¬Ã¿µ±CSSÎļþ±»ÐÞ¸Äʱ£¬Ö»ÐèÒª¸üÐÂÎļþÃûÖеİ汾ºÅ¼´¿É¡£
ÁíÍ⣬Nginx»¹ÌṩÁËÒ»¸öreloadµÄÏÂÁ¿ÉÒÔÔÚ²»×èֹЧÀÍÆ÷µÄÇéÐÎÏÂÖØмÓÔØÉèÖÃÎļþ¡£ÀýÈ磬¿ÉÒÔÖ´ÐÐÒÔÏÂÏÂÁîÀ´ÖØмÓÔØNginxµÄÉèÖÃÎļþ£º
$ nginx -s reload
µÇ¼ºó¸´ÖÆ
ÕâÑùÒ»À´£¬Nginx½«»áÖØжÁÈ¡ÉèÖÃÎļþ£¬²¢ÇÒ¸üеÄÉèÖûáÁ¬Ã¦ÉúЧ¡£
×ܽá
ͨ¹ýʹÓÃNginx¾ÙÐо²Ì¬Îļþ»º´æ£¬¿ÉÒÔÏÔÖøÌá¸ßÍøÕ¾µÄÐÔÄܺͻá¼ûËÙÂÊ¡£ÔÚ±¾ÎÄÖУ¬ÎÒÃÇÏÈÈÝÁËÔõÑùÉèÖÃNginxÒÔÆôÓþ²Ì¬Îļþ»á¼û»ººÍ´æ¹¦Ð§£¬²¢ÌṩÁËÏìÓ¦µÄ´úÂëʾÀýºÍÑéÖ¤ÒªÁ졣ϣÍûÕâЩÄÚÈÝÄܹ»×ÊÖúÄãÓÅ»¯ÄãµÄÍøÕ¾ÐÔÄÜ¡£
ÒÔÉϾÍÊÇÔõÑùʹÓÃNginx¾ÙÐиßÐÔÄܵľ²Ì¬Îļþ»º´æµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡