Nginx»º´æÕûÀíÉèÖã¬ÓÅ»¯ÍøÕ¾¾²Ì¬×ÊÔ´¸üÐÂ
nginx»º´æÕûÀíÉèÖã¬ÓÅ»¯ÍøÕ¾¾²Ì¬×ÊÔ´¸üÐÂ
СÐò£º
ÔÚÍøÕ¾¿ª·¢Àú³ÌÖУ¬¾³£»áÓо²Ì¬×ÊÔ´µÄ¸üУ¬ÈçCSS¡¢JavaScriptºÍͼƬµÈ¡£È»¶ø£¬ÓÉÓÚä¯ÀÀÆ÷µÄ»º´æ»úÖÆ£¬»á¼ûÕß¿ÉÄÜÎÞ·¨Á¬Ã¦»ñÈ¡µ½×îа汾µÄ¾²Ì¬×ÊÔ´¡£ÎªÏàʶ¾öÕâ¸öÎÊÌ⣬ÎÒÃÇ¿ÉÒÔʹÓÃNginx¾ÙÐлº´æÕûÀíÉèÖã¬ÒÔÓÅ»¯ÍøÕ¾¾²Ì¬×ÊÔ´µÄ¸üС£
Ò»¡¢Nginx»º´æÉèÖÃ
Ê×ÏÈ£¬ÎÒÃÇÐèÒªÔÚNginxµÄÉèÖÃÎļþnginx.confÖÐÌí¼ÓÒÔÏÂÖ¸ÁîÀ´ÉèÖûº´æÏà¹ØµÄÉèÖãº
http { ... proxy_cache_path /path/to/cache levels=1:2 keys_zone=cache_zone:10m max_size=10g inactive=60m; ... server { ... location ~* .(css|js|png|jpg|jpeg|gif|ico)$ { expires 30d; add_header Pragma public; add_header Cache-Control "public"; proxy_cache cache_zone; proxy_cache_key $scheme$proxy_host$uri$is_args$args; proxy_cache_valid 200 301 302 404 1d; } ... } ... }
µÇ¼ºó¸´ÖÆ
proxy_cache_path£ºÉèÖûº´æĿ¼µÄ·¾¶¡£levels=1:2ÌåÏÖÔÚ»º´æĿ¼ÏÂʹÓÃÁ½¼¶×ÓĿ¼À´´æ´¢»º´æÎļþ£¬Õâ¿ÉÒÔÌá¸ßÎļþµÄ²éÕÒËÙÂÊ¡£keys_zoneΪ»º´æÇøÓòµÄÃû³Æ£¬10mÌåÏÖ·ÖÅÉ10MBµÄÄÚ´æÓÃÓÚ»º´æË÷Òý¡£max_sizeÌåÏÖ»º´æÎļþµÄ×î´ó¾Þϸ£¬inactiveÌåÏÖÔÚָ׼ʱ¼äûÓб»»á¼ûʱ£¬»º´æÎļþ»á±»É¾³ý¡£
location£ºÓÃÓÚÆ¥ÅäÐèÒª±»»º´æµÄ¾²Ì¬×ÊÔ´Îļþ¡£ÔÚ´ËÀýÖУ¬Ê¹ÓÃÕýÔò±í´ïʽƥÅäCSS¡¢JavaScript¡¢Í¼Æ¬µÈÎļþ£¬²¢ÉèÖûº´æµÄÓâÆÚʱ¼äΪ30Ìì¡£
add_header£ºÌí¼ÓHTTPÏìӦͷÐÅÏ¢£¬ÉèÖÃPragmaΪpublicºÍCache-ControlΪpublic£¬ÒÔÈ·±£»º´æ¿ÉÒÔ±»¹«¹²»º´æЧÀÍÆ÷ºÍä¯ÀÀÆ÷»º´æ¡£
¶þ¡¢Nginx»º´æÕûÀíÉèÖÃ
µ±ÎÒÃǸüÐÂÁËÍøÕ¾µÄ¾²Ì¬×ÊÔ´Îļþºó£¬ÐèÒª½«»º´æÖеľɰ汾Îļþɨ³ý£¬ÒÔʹ»á¼ûÕß¿ÉÒÔ»ñÈ¡µ½×îеľ²Ì¬×ÊÔ´¡£ÎªÁËʵÏÖÕâÒ»µã£¬ÎÒÃÇ¿ÉÒÔÔÚNginxµÄÉèÖÃÎļþÖÐÌí¼ÓÒÔÏ´úÂ룺
http { ... proxy_cache_path /path/to/cache levels=1:2 keys_zone=cache_zone:10m max_size=10g inactive=60m; ... server { ... location /purge-cache { internal; proxy_cache_purge cache_zone "$scheme$proxy_host$uri$is_args$args"; } ... } ... }
µÇ¼ºó¸´ÖÆ
location£º½ç˵һ¸ö/purge-cacheµÄURL£¬ÓÃÓÚ´¥·¢»º´æÕûÀí²Ù×÷¡£internalÌåÏÖÕâ¸öURLÖ»¶ÔÄÚ²¿»á¼ûÓÐÓá£
proxy_cache_purge£ºÉ¨³ýÖ¸¶¨µÄURL¶ÔÓ¦µÄ»º´æÎļþ¡£
Èý¡¢´úÂëʾÀý
¼ÙÉèÎÒÃÇÍøÕ¾ÖеÄCSSÎļþλÓÚhttp://example.com/static/css/style.css£¬ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏ´úÂëÀ´ÕûÀí»º´æÖеĸÃÎļþ£º
curl -X PURGE http://example.com/purge-cache/static/css/style.css
µÇ¼ºó¸´ÖÆ
Õâ¸öÇëÇ󽫻áʹnginxɨ³ý»º´æÖиÃURL¶ÔÓ¦µÄ»º´æÎļþ£¬Ï´λá¼û¸ÃURLʱ½«»áÖØÐÂÌìÉú»º´æ¡£
½áÂÛ£º
ͨ¹ýÉèÖÃNginxµÄ»º´æÕûÀí£¬ÎÒÃÇ¿ÉÒÔÓÅ»¯ÍøÕ¾¾²Ì¬×ÊÔ´µÄ¸üС£µ±ÎÒÃǸüÐÂÁ˾²Ì¬×ÊԴʱ£¬Ö»ÐèÒª·¢ËÍÒ»¸öÕûÀí»º´æµÄÇëÇ󣬾ͿÉÒÔʹ»á¼ûÕß»ñÈ¡µ½×îеÄ×ÊÔ´Îļþ£¬Ìá¸ßÍøÕ¾µÄÐÔÄܺÍÓû§ÌåÑé¡£
²Î¿¼×ÊÁÏ£º
Nginx¹Ù·½Îĵµ£ºhttps://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_purge
ÒÔÉϾÍÊÇNginx»º´æÕûÀíÉèÖã¬ÓÅ»¯ÍøÕ¾¾²Ì¬×ÊÔ´¸üеÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡