ÔõÑùʹÓÃNginx¾ÙÐÐHTTPÇëÇóµÄÐÔÄÜÓÅ»¯
ÔõÑùʹÓÃnginx¾ÙÐÐhttpÇëÇóµÄÐÔÄÜÓÅ»¯
ÕªÒª£ºNginxÊÇÒ»¸ö¸ßÐÔÄܵÄWebЧÀÍÆ÷£¬Ò²ÊÇÒ»¸öÇ¿Ê¢µÄ·´ÏòÊðÀíЧÀÍÆ÷¡£Ëü¿ÉÒÔͨ¹ý¶àÖÖ·½·¨À´Ìá¸ßHTTPÇëÇóµÄÐÔÄÜ¡£±¾ÎĽ«ÏÈÈÝһЩʹÓÃNginx¾ÙÐÐHTTPÇëÇóÐÔÄÜÓÅ»¯µÄ¼¼ÇÉ£¬²¢ÌṩÏìÓ¦µÄ´úÂëʾÀý¡£
ÆôÓûº´æ
ÆôÓÃNginxµÄ»º´æ¹¦Ð§¿ÉÒÔÏÔÖøïÔÌЧÀÍÆ÷µÄ¸ºÔغÍÇëÇóÏìӦʱ¼ä¡£ÏÂÃæÊÇÒ»¸öÆôÓûº´æµÄʾÀýÉèÖãº
http { ... proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off; server { ... location / { proxy_pass http://backend; proxy_cache my_cache; proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m; } } }
µÇ¼ºó¸´ÖÆ
ÉÏÊöʾÀýÖУ¬ÎÒÃÇͨ¹ýproxy_cache_pathÖ¸ÁîÉèÖÃÁË»º´æ·¾¶ºÍÏà¹ØÑ¡ÏȻºóÔÚlocation¿éÖÐʹÓÃÁËproxy_cacheÖ¸ÁîÆôÓûº´æ£¬²¢Í¨¹ýproxy_cache_validÖ¸ÁîÖ¸¶¨²î±ðµÄÏìÓ¦ÂëµÄ»º´æÓÐÓÃʱ¼ä¡£
ÆôÓÃGzipѹËõ
ÆôÓÃGzipѹËõ¿ÉÒÔ¼õС´«ÊäÎļþµÄ¾Þϸ£¬½ø¶øïÔÌÍøÂç´ø¿íµÄÕ¼Óá£ÏÂÃæÊÇÒ»¸öÆôÓÃGzipѹËõµÄʾÀýÉèÖãº
http { ... gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_types text/plain text/css application/json application/javascript text/xml application/xml+rss application/atom+xml image/svg+xml; server { ... location / { proxy_pass http://backend; proxy_set_header Accept-Encoding ""; } } }
µÇ¼ºó¸´ÖÆ
ÉÏÊöʾÀýÖУ¬ÎÒÃÇͨ¹ýgzip onÖ¸ÁîÆôÓÃÁËGzipѹËõ£¬²¢Í¨¹ýgzip_typesÖ¸ÁîÖ¸¶¨ÁËÒª¾ÙÐÐѹËõµÄÎļþÀàÐÍ¡£
ʹÓÃHTTP/2
HTTP/2ÊÇÒ»ÖÖеÄÍøÂçÐÒ飬Ïà½ÏÓÚHTTP/1.1ÓÐÐí¶àÐÔÄÜˢС£ÆôÓÃHTTP/2¿ÉÒÔÌṩ¸ü¸ßµÄ²¢·¢¶È²¢ïÔÌÑÓ³Ù¡£ÏÂÃæÊÇÒ»¸öÆôÓÃHTTP/2µÄʾÀýÉèÖãº
http { ... server { ... listen 443 ssl http2; ssl_certificate /path/to/certificate.crt; ssl_certificate_key /path/to/private.key; ... } }
µÇ¼ºó¸´ÖÆ
ÉÏÊöʾÀýÖУ¬ÎÒÃÇͨ¹ýlistenÖ¸ÁîÉèÖÃÁËʹÓÃ443¶Ë¿Ú²¢ÆôÓÃÁËHTTP/2¡£
ʹÓÃNginx»º´æ¼ÓËÙЧÀÍ
Nginx¿ÉÒÔ×÷Ϊһ¸ö»º´æ¼ÓËÙЧÀÍ£¬ÊðÀíºó¶ËЧÀÍÆ÷µÄÇëÇóÒÔ¼õÇáºó¶ËµÄ¸ºÔØ¡£ÏÂÃæÊÇÒ»¸öÆôÓûº´æ¼ÓËÙЧÀ͵ÄʾÀýÉèÖãº
http { ... upstream backend { server backend1.example.com; server backend2.example.com; } server { ... location / { proxy_pass http://backend; proxy_cache my_cache; proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m; } } }
µÇ¼ºó¸´ÖÆ
ÉÏÊöʾÀýÖУ¬ÎÒÃÇͨ¹ýupstreamÖ¸Áî½ç˵Á˺ó¶ËЧÀÍÆ÷µÄÁÐ±í£¬È»ºóÔÚlocation¿éÖÐʹÓÃÁËproxy_passÖ¸ÁîÀ´ÊðÀíºó¶ËЧÀÍÆ÷µÄÇëÇó¡£
½áÂÛ£º
ͨ¹ýÆôÓûº´æ¡¢ÆôÓÃGzipѹËõ¡¢Ê¹ÓÃHTTP/2ºÍʹÓÃNginx»º´æ¼ÓËÙЧÀ͵ȷ½·¨£¬ÎÒÃÇ¿ÉÒÔÏÔÖøÌá¸ßHTTPÇëÇóµÄÐÔÄÜ¡£ÒÔÉÏÊÇһЩʹÓÃNginx¾ÙÐÐHTTPÇëÇóÐÔÄÜÓÅ»¯µÄ¼¼ÇɺÍÏìÓ¦µÄ´úÂëʾÀý¡£
²Î¿¼×ÊÁÏ£º
Nginx Documentation: https://nginx.org/en/docs/
Nginx Caching: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache
Nginx Gzip Compression: https://nginx.org/en/docs/http/ngx_http_gzip_module.html
Nginx HTTP/2: https://nginx.org/en/docs/http/http2_module.html
Nginx Reverse Proxy: https://nginx.org/en/docs/http/ngx_http_proxy_module.html
ÒÔÉϾÍÊÇÔõÑùʹÓÃNginx¾ÙÐÐHTTPÇëÇóµÄÐÔÄÜÓÅ»¯µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡