📜 ⬆️ ⬇️

Caching FastCGI requests in nginx

Good morning, Habr!

In this article, I will give an example of the nginx configuration for caching FastCGI requests. If desired, it can be used to protect against habraeffekt, in part from DDoS'a and, as an option, to facilitate the life of the server with a high load.

In the section “http” we declare a fastcgi_cache cache zone, with cache storage in the / tmp / nginx folder with 2 nesting levels, with a maximum size of 256MB and a cache of 16MB keys (objects that are not used for more than 1 day will be automatically deleted):
fastcgi_cache_path / tmp / nginx / levels = 1: 2 keys_zone = fastcgi_cache: 16m max_size = 256m inactive = 1d;

Further, in the section "server" we rule the corresponding location:
 location ~ \ .php $ {
             # Standard configuration for php
             fastcgi_pass unix: /tmp/php-fcgi.sock;
             fastcgi_index index.php;
             fastcgi_param SCRIPT_FILENAME / usr / local / www / somedir / $ fastcgi_script_name;
             include fastcgi_params;
             fastcgi_param DOCUMENT_ROOT / usr / local / www / somedir /;
            
             fastcgi_pass_header Cookie;  # Required to pass a cookie to the corresponding variables, for example a cookie named phpsessid will be in the $ cookie_phpsessid variable

             fastcgi_ignore_headers Cache-Control Expires Set-Cookie;  # Ignore caching headers received from FastCGI server

             fastcgi_cache_key "$ server_addr: $ server_port $ request_uri | $ cookie_phpsessid";  # We form a unique key;  in this case, we distinguish users using $ cookie_phpsessid

             fastcgi_cache fastcgi_cache;  # We are talking about using the fastcgi_cache above-declared cache zone

             fastcgi_temp_path / tmp / nginx / temp 1 2;  # Specify the folder for storing temporary files

             update_time_add_ http_500;  # Use the cache option (even if it is outdated) in case of an error

             fastcgi_cache_valid 10s;  # Life time for answer cache 200, 301 & 302

             #fastcgi_cache_valid any 10s;  # This way you can cache any answers.
             }

The config was tested on the nginx version> = 0.7.60 (on => 0.8.1 should work, but was not tested).

Documentation: Module directives ngx_http_fastcgi_module , Changelog .
')
upd: If you do not ignore the Cache-Control and Expires headers, nginx behaves according to their content (which, in principle, is logical).

upd / 01/28/2011: Set-Cookie has been added to fastcgi_ignore_headers (since nginx / 0.8.44)

upd / 07.02.2011: it is necessary to implement the separation of search engine crawlers, since by ignoring cookies, they can be thrown out.

Source: https://habr.com/ru/post/71501/


All Articles