Nginx is one of the best popular webservers today. Its popularity is due to the fact that it is very fast and easy to set up. Other side of this popularity - nginx is often being a target of malicious attacks. So, if your nginx is not limited by available resources, your server may totally "fall" when nginx spent all system resources. That's why you should control and limit resources Nginx consumed.
All limits are sets in nginx configuration file. I will describe it on Ubuntu 20.04 as example. All changes will be made in /etc/nginx/nginx.conf file. Each directive should end with a semicolon. I will describe the most important parameters further.
Global settings
These settings will affect on whole server. Parameters description is:
- worker_connections - this option defines how many simultaneous connections are possible for one worker (special "unit" which communicate between nginx and operation system core). Workers count it depends of how much CPU cores and RAM available on your server;
- multi_accept - this directives allows workers to handle a few processes simultaneously. It will create processes queue, tasks will be handled one-by-one;
- mutex_accept_delay - this parameter defines a delay between restart of handled tasks;
- use - a method of processing. The best set for Linux servers is epoll;
- limit_conn - this directive will limit connections. It may be set in various places, all restrictions will be working. On the screenshot below I set total connections as 5 per one IP and 2 for /download folder:
Disk operations
These settings define how to nginx operate with disk drive:
- sendfile on - this option allows to webserver to "exchange" small files data in kernel space, without sending it to the app space. It makes nginx data handling much faster;
- aio on - this directive provide multi-thread read/write disk operations.
Compression and caching
You may cache some data to do nginx faster. Compression will reduce traffic flow:
- gzip on - this option turn compression on;
- gzip_comp_level - compression level. Higher count is much compression;
- gzip_types - define of types of files to be compressed. E.g. text is good to compress, but pictures is not.
- open_file_cache - allow file caching;
- open_file_cache_valid - time to store cache;
- open_file_cache_errors - this option allows caching errors like "access denied". It may be helpful to prevent massive simultaneous connects attack;
Security settings
You may restrict access for scrapers, bots, downloaders etc. Just add construct like below to restricted location:
return 403;
}
Also, you can allow access to some website areas via defined IPs only. It could be useful to restrict access to admin area e.g.:
## allow access from your IP
allow xxx.xxx.xxx.xxx/32;
## drop all other connections
deny all;
}
Conclusion
In this article I described how to optimize your nginx works and gave some advices about base security improvements.