Tips and Tricks for configuring Nginx
Nginx Tip 1. Organize the Nginx config files
Usually the config files are located in /etc/nginx
It is possible to organize config files like installing Apache on Ubuntu / Debian:
1 2 3 4 5 6 7 8 9 10 | ## Main configuration file ## /etc/nginx/nginx.conf ## Virtualhost configuration files on ## /etc/nginx/sites-available/ /etc/nginx/sites-enabled/ ## Other config files on (if needed) ## /etc/nginx/conf.d/ |
Virtualhost files have 2 folders, because directory sites-available
can accommodate any configuration files in public, such as the use to test configs, configs are clone, created new configs, old config, …. And sites-enabled
only contains those configs that are actually enabled, actually just symbolic links to the sites-available
directory.
You need to add the include of config files added in the nginx.conf
file:
1 2 3 4 5 6 | ## Load virtual host conf files. ## include /etc/nginx/sites-enabled/*; ## Load another configs from conf.d/ ## include /etc/nginx/conf.d/*; |
Nginx Tip 2. Identify Nginx worker_processes and worker_connections
The default setting is fine for worker_ processes and worker_connections, but these values can be slightly optimized:
max_clients = worker_processes * worker_connections
A basic Nginx setup can handle hundreds of concurrent connections:
1 2 3 | worker_processes 1; worker_connections 1024; |
Normally 1000 concurrent connection / trên 1 server
is good, but sometimes other components like the drives on the server may be slow, and it will cause Nginx to be locked during I / O operations. To avoid locking, use config like this: 1 worker_precess / on 1 processor core, like:
Worker Processes
1 2 | worker_processes [number of processor cores]; |
To check how many processor cores you have, run the following command:
1 2 3 4 5 6 | <span class="token function">cat</span> /proc/cpuinfo <span class="token operator">|</span> <span class="token function">grep</span> processor processor <span class="token keyword">:</span> 0 processor <span class="token keyword">:</span> 1 processor <span class="token keyword">:</span> 2 processor <span class="token keyword">:</span> 3 |
There are 4 cores and worker_processes that can be configured as follows:
1 2 | worker_processes 4; |
Worker Connections
I personally stick with 1024 worker connections, because I have no reason to raise this value. But if for example 4096 connections per second is not enough, you can try to double this number and set 2048 connections for each process.
The final configuration of worker_processes might be as follows:
1 2 | worker_connections 1024; |
Nginx Tip 3. – Hide Nginx Server Tokens / Hide Nginx version
For security reasons, hide the server tokens / hide the Nginx version, especially if you run an older version of Nginx. This is very simple, you just need to set server_tokens off
in http/server/location
section, as follows:
1 2 | server_tokens off; |
Nginx Tip 4. – Nginx Request / Upload Max Body Size (client_max_body_size)
If you want to allow users to upload something over HTTP then you can increase the post size . This is done by changing the value of client_max_body_size
located in http/server/location
section. The default is 1 Mb, but it can be set to 20 Mb and also increase the buffer size with the following configuration:
1 2 3 | client_max_body_size 20m; client_body_buffer_size 128k; |
If you encounter the following error, you should know that client_max_body_size
too low:
1 2 | “Request Entity Too Large” (413) |
Nginx Tip 5. – Nginx Cache Control for Static Files (Browser Cache Control Directives)
Browser caching is necessary if you want to save resources and bandwith. It is simple to set up with Nginx, turn off log (access log and not found log) and set expires headers to 360 days.
1 2 3 4 5 6 | location ~* .(jpg|jpeg|gif|png|css|js|ico|xml)$ { access_log off; log_not_found off; expires 360d; } |
If you want to add special headers for different file types or time expires, you can configure each file type.
Nginx Tip 6. – Nginx Pass PHP requests to PHP-FPM
Here you can use the default tpc / ip stack or use the Unix socket connection directly. You must also set up PHP-FPM listen to exactly the same ip: port or unix socket (with Unix socket must also have socket permission). The default setting is to use ip: port (127.0.0.1:9000) of course you can change the ips and ports that PHP-FPM listens. This is a very basic configuration with an example of a Unix socket:
1 2 3 4 5 6 7 8 9 10 | # Pass PHP scripts to PHP-FPM location ~* .php$ { fastcgi_index index.php; fastcgi_pass 127.0.0.1:9000; #fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param SCRIPT_NAME $fastcgi_script_name; } |
That means you can run PHP-FPM and Nginx on 2 different servers.
Nginx Tip 7. – Prevent access to hidden files with Nginx
It is very common that server root or other public directories have hidden files, beginning with a dot (.) And normally they are not for website users. The public directory may contain version control files and directories, such as .svn, IDE properties files and .htaccess files. The following is a config that refuses to access and turn off logging for all hidden files.
1 2 3 4 5 6 | location ~ /. { access_log off; log_not_found off; deny all; } |
Tips and tricks for configuring PHP-FPM
PHP-FPM Tip 1. – PHP-FPM Configuration files
Usually the PHP-FPM configuration files are located in /etc/php-fpm.conf
and the /etc/php-fpm.d
path. This is usually a great start and all pool configs will move to /etc/php-fpm.d
. You need to add the following include to the php-fpm.conf file:
1 2 | include=/etc/php-fpm.d/*.conf |
PHP-FPM Tip 2. – Tweaking PHP-FPM Global Configuration
Set up emergency_restart_threshold
, emergency_restart_interval
and process_control_timeout
. The default values for these options are all off
, but I think it’s better to use the following examples of options:
1 2 3 4 | emergency_restart_threshold 10 emergency_restart_interval 1m process_control_timeout 10s |
What does this all mean? If 10 PHP-FPM child processes exit with SIGSEGV or SIGBUS within 1 minute then PHP-FPM will automatically restart. This configuration also sets a 10-second time limit for child processes to wait for responses on signals from the master.
PHP-FPM Tip 3. – PHP-FPM Pools Configuration
With PHP-FPM, it is possible to use different pools for different websites and allocate resources very accurately and even use different groups and users for each pool. Here is an example of the file structure for PHP-FPM pools for three different websites (or in fact, three different parts of the same website):
1 2 3 4 | /etc/php-fpm.d/site.conf /etc/php-fpm.d/blog.conf /etc/php-fpm.d/forums.conf |
The configuration examples for the pools are as follows:
/etc/php-fpm.d/site.conf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | [site] listen = 127.0.0.1:9000 user = site group = site request_slowlog_timeout = 5s slowlog = /var/log/php-fpm/slowlog-site.log listen.allowed_clients = 127.0.0.1 pm = dynamic pm.max_children = 5 pm.start_servers = 3 pm.min_spare_servers = 2 pm.max_spare_servers = 4 pm.max_requests = 200 listen.backlog = -1 pm.status_path = /status request_terminate_timeout = 120s rlimit_files = 131072 rlimit_core = unlimited catch_workers_output = yes env[HOSTNAME] = $HOSTNAME env[TMP] = /tmp env[TMPDIR] = /tmp env[TEMP] = /tmp |
/etc/php-fpm.d/blog.conf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | [blog] listen = 127.0.0.1:9001 user = blog group = blog request_slowlog_timeout = 5s slowlog = /var/log/php-fpm/slowlog-blog.log listen.allowed_clients = 127.0.0.1 pm = dynamic pm.max_children = 4 pm.start_servers = 2 pm.min_spare_servers = 1 pm.max_spare_servers = 3 pm.max_requests = 200 listen.backlog = -1 pm.status_path = /status request_terminate_timeout = 120s rlimit_files = 131072 rlimit_core = unlimited catch_workers_output = yes env[HOSTNAME] = $HOSTNAME env[TMP] = /tmp env[TMPDIR] = /tmp env[TEMP] = /tmp |
/etc/php-fpm.d/forums.conf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | [forums] listen = 127.0.0.1:9002 user = forums group = forums request_slowlog_timeout = 5s slowlog = /var/log/php-fpm/slowlog-forums.log listen.allowed_clients = 127.0.0.1 pm = dynamic pm.max_children = 10 pm.start_servers = 3 pm.min_spare_servers = 2 pm.max_spare_servers = 4 pm.max_requests = 400 listen.backlog = -1 pm.status_path = /status request_terminate_timeout = 120s rlimit_files = 131072 rlimit_core = unlimited catch_workers_output = yes env[HOSTNAME] = $HOSTNAME env[TMP] = /tmp env[TMPDIR] = /tmp env[TEMP] = /tmp |
This is just an example for configing many different site pools.
PHP-FPM Tip 4. – PHP-FPM Pool Process Manager (pm) Configuration
The best way to use the PHP-FPM process manager is to use dynamic process management, so PHP-FPM processes should only be started when needed. This is a style setting that is similar to the Nginx worker_processes and worker_connections settings. So very high value does not mean everything is good. Every process consumes memory and of course if the site has very high traffic and a lot of memory then higher values will be chosen, but servers, like VPS (Virtual Private Servers) memory are often restricted. limit at 256 Mb, 512 Mb, 1024 Mb. This low RAM is sufficient to handle very high traffic (even dozens of requests per second), if it is used wisely.
It’s good to check how many PHP-FPM processes a server can handle easily, first start Nginx and PHP-FPM and download some PHP pages, preferably all the heaviest pages. Then check the memory usage for each example of PHP-FPM processes with command top
or htop
on Linux. Assuming that the server has 512 Mb and 220 Mb memory can be used for PHP-FPM, each process uses 24 Mb of RAM (some huge content management systems with plugins can easily use 20 -40 Mb / per PHP page request or even more). Then, just calculate the server’s max_children
value: 220/24 = 9.17
So a good pm.max_children
value is 9
. This is just based on a fast average and the latter could be something else when you see longer memory usage / per process. After the test is completed, it is much easier to set the pm.start_servers
value, pm.min_spare_servers
value and pm.max_spare_servers
values.
Example configuration might be as follows:
1 2 3 4 5 6 | pm.max_children = 9 pm.start_servers = 3 pm.min_spare_servers = 2 pm.max_spare_servers = 4 pm.max_requests = 200 |
Refer to the original article here