ÔõÑùʵÏÖNginxµÄ·´ÏòÊðÀí»º´æÉèÖÃ
ÔõÑùʵÏÖNginxµÄ·´ÏòÊðÀí»º´æÉèÖÃ
NginxÊÇÒ»ÖÖ¸ßÐÔÄܵÄWebЧÀÍÆ÷ºÍ·´ÏòÊðÀíЧÀÍÆ÷£¬¿ÉÒÔͨ¹ýÉèÖÃʵÏÖ·´ÏòÊðÀí»º´æ£¬Ìá¸ßÍøÕ¾µÄÐÔÄܺÍÓû§ÌåÑé¡£±¾ÎĽ«ÏêϸÏÈÈÝÔõÑùÉèÖÃNginxµÄ·´ÏòÊðÀí»º´æ£¬²¢ÌṩÏêϸµÄ´úÂëʾÀý¡£
¿ªÆôNginxµÄ»º´æ¹¦Ð§
Ê×ÏÈ£¬ÐèÒªÔÚNginxµÄÉèÖÃÎļþÖпªÆô»º´æ¹¦Ð§¡£·¿ªNginxµÄÉèÖÃÎļþ£¨Ò»Ñùƽ³£Î»ÓÚ/etc/nginx/nginx.conf£©£¬ÕÒµ½http¿é£¬²¢Ìí¼ÓÒÔÏ´úÂ룺
http { ... proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off; ... }
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂëÖУ¬/path/to/cacheÊÇNginx»º´æÎļþÉúÑĵÄ·¾¶£¬ÔÚÏÖʵʹÓÃʱÐèҪƾ֤ЧÀÍÆ÷µÄÏÖÕæÏàÐξÙÐÐÐ޸ġ£keys_zone=my_cache:10mÊÇÉèÖûº´æÇøµÄÃû³ÆºÍ¿ÉÓÿռä¾Þϸ£¬¿ÉÒÔƾ֤ÏÖʵÐèÇó¾ÙÐÐÐ޸ġ£max_size=10gÊÇÉèÖûº´æÎļþµÄ×î´óÈÝÁ¿£¬¿ÉÒÔƾ֤ЧÀÍÆ÷µÄ´ÅÅÌ¿Õ¼ä¾ÙÐе÷½â¡£inactive=60mÊÇÉèÖûº´æÎļþµÄÓâÆÚʱ¼ä£¬Áè¼Ý¸Ãʱ¼ä½«±»É¾³ý¡£use_temp_path=offÊǽûÓÃÔÝʱÎļþ´æ´¢Â·¾¶¡£
ÉèÖÃNginx·´ÏòÊðÀí»º´æ
½ÓÏÂÀ´£¬ÐèÒªÔÚNginxµÄÉèÖÃÎļþÖÐÉèÖ÷´ÏòÊðÀí»ººÍ´æµÄÏêϸ¹æÔò¡£ÔÚserver¿éÖÐÌí¼ÓÒÔÏ´úÂ룺
server { ... location / { proxy_pass http://backend; proxy_set_header Host $host; proxy_cache my_cache; proxy_cache_valid 200 301 302 404 1h; proxy_cache_use_stale updating; proxy_cache_background_update on; } ... }
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂëÖУ¬proxy_pass http://backend½«ÇëÇóת·¢¸øºó¶ËЧÀÍÆ÷¡£proxy_set_header Host $hostÓÃÓÚת´ïÇëÇóµÄÓòÃû»òIPµØµã¡£proxy_cache my_cacheÖ¸¶¨Ê¹ÓõĻº´æÇøÃû³Æ¡£proxy_cache_valid 200 301 302 404 1hÉèÖûº´æµÄÓÐÓÃÆÚ£¬200¡¢301¡¢302ºÍ404ÊǶÔÓ¦µÄHTTP״̬Â룬1hÌåÏÖһСʱ¡£proxy_cache_use_stale updatingÉèÖøüлº´æʱʹÓÃÓâÆÚÊý¾Ý¡£proxy_cache_background_update onÆôÓúǫ́¸üлº´æ¡£
ÉèÖÃNginx»º´æµÄ¸½¼Ó¹æÔò
ÈôÊÇÐèÒª¶ÔÌض¨µÄURL¾ÙÐлº´æ»ò²»»º´æ£¬¿ÉÒÔÌí¼Ó¸ü¶àµÄÉèÖùæÔò¡£ÒÔÏÂÊÇһЩ³£ÓõÄʾÀý´úÂ룺
location /static { proxy_pass http://backend; proxy_set_header Host $host; proxy_cache my_cache; proxy_cache_valid 200 301 302 404 7d; proxy_cache_use_stale updating; proxy_cache_background_update on; } location /no-cache { proxy_pass http://backend; proxy_set_header Host $host; proxy_cache off; }
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂëÖУ¬/staticÌåÏÖÐèÒª»º´æµÄURL·¾¶£¬7dÌåÏÖ»º´æÓÐÓÃÆÚΪ7Ìì¡£/no-cacheÌåÏÖ²»ÐèÒª»º´æµÄURL·¾¶£¬proxy_cache off½ûÓûº´æ¡£
ÖØÆôNginxЧÀÍÆ÷
Íê³ÉÒÔÉÏÉèÖúó£¬ÐèÒªÖØÐÂÆô¶¯NginxЧÀÍÆ÷£¬Ê¹ÉèÖÃÉúЧ¡£ÔÚÏÂÁîÐÐÖÐÖ´ÐÐÒÔÏÂÏÂÁ
sudo service nginx restart
µÇ¼ºó¸´ÖÆ
ÑéÖ¤»º´æÉèÖÃ
¿ÉÒÔʹÓÃä¯ÀÀÆ÷»á¼ûÍøÕ¾£¬²¢ÔÚÏìӦͷÖÐÉó²éÊÇ·ñ±£´æ»º´æÏà¹ØµÄ×ֶΡ£¿ÉÒÔͨ¹ýÔÚ¿ª·¢Õß¹¤¾ßÖÐÉó²éNetwork tab»òʹÓÃcurlÏÂÁî¾ÙÐÐÑéÖ¤¡£
curl -I http://your-website.com
µÇ¼ºó¸´ÖÆ
ÔÚÏìӦͷÖУ¬¿ÉÒÔÉó²éCache-Control¡¢Last-Modified¡¢X-CacheºÍX-Cache-StatusµÈ×ֶΣ¬ÑéÖ¤·´ÏòÊðÀí»º´æÉèÖÃÊÇ·ñÉúЧ¡£
×ܽá
±¾ÎÄÏÈÈÝÁËÔõÑùʵÏÖNginxµÄ·´ÏòÊðÀí»º´æÉèÖá£Í¨¹ýÉèÖÃNginxµÄ»º´æ¹¦Ð§£¬¿ÉÒÔ´ó·ù¶ÈÌá¸ßÍøÕ¾µÄÐÔÄܺÍÓû§ÌåÑé¡£ÐèҪעÖصÄÊÇ£¬ÏêϸµÄÉèÖùæÔòÐèҪƾ֤ЧÀÍÆ÷µÄÏÖÕæÏàÐξÙÐе÷½â£¬È·±£»º´æÉèÖõÄÊÊÓÃÐÔºÍÎȹÌÐÔ¡£
ÒÔÉϾÍÊÇÔõÑùʵÏÖNginxµÄ·´ÏòÊðÀí»º´æÉèÖõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡