Optimizing Nginx Configuration for high traffic websites

use of Nginx to optimize the website's performance under high traffic debian ubuntu

Nginx is a popular open-source web server and reverse proxy that is widely used to serve high-traffic websites. In order to optimize Nginx configuration for high traffic websites, there are several best practices that you can follow. In this article, we will discuss some of these best practices.

Understand Your Traffic Patterns

The first step in optimizing Nginx configuration for high traffic websites is to understand your traffic patterns. You should be aware of the number of requests your server receives and the types of requests it receives. You should also be aware of the peak traffic times and the geographic distribution of your visitors.

This information will help you determine the appropriate server hardware and configuration to handle your traffic. For example, if you have a high volume of requests, you may need to increase the number of worker processes and connections that Nginx can handle.

Optimize Your Server Hardware

The performance of your Nginx server is highly dependent on the hardware it runs on. To optimize Nginx configuration for high traffic websites, you should ensure that your server hardware is up to the task.

You should choose a server with a high-speed processor, plenty of RAM, and fast storage. SSDs are recommended as they offer much faster read and write speeds compared to traditional hard drives. You should also consider using multiple servers to distribute the load and provide redundancy.

Optimize Your Nginx Configuration

Once you have optimized your server hardware, it is time to optimize your Nginx configuration. Here are some tips to help you optimize your Nginx configuration for high traffic websites:

Note :
you can find the config files in /etc/nginx/nginx.conf for global config
and your websites configs should be in /etc/ngnix/sites-enabled/
Make sure to restart / reload Nginx after changing your settings:

Reload server without downtime :

$ sudo ngnix -s reload

Restart nginx service :

$ sudo systemctl restart nginx

Increase the Number of Worker Processes and Connections

To increase the number of worker processes and connections, you can add the following directives to your Nginx configuration file:

worker_processes auto;
worker_rlimit_nofile 100000;
events {
    worker_connections 100000;
}
  • worker_processes: This directive sets the number of worker processes. The auto value tells Nginx to automatically determine the optimal number of worker processes based on the number of CPU cores available.
  • worker_rlimit_nofile: This directive sets the maximum number of file descriptors that each worker process can open. This value should be set high enough to accommodate the number of connections that your server is handling.
  • events: This block specifies the event handling mechanism used by Nginx. The worker_connections directive sets the maximum number of connections that each worker process can handle.

Use Gzip Compression

To enable Gzip compression, you can add the following directive to your Nginx configuration file:

gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
  • gzip: This directive enables Gzip compression.
  • gzip_types: This directive specifies the MIME types of files that should be compressed. The above example specifies common text-based file types as well as JSON and JavaScript files.

Use Caching

To enable caching, you can use Nginx’s built-in caching module or a caching proxy such as Varnish. Here is an example of enabling server-side caching using Nginx’s built-in caching module:

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
server {
    ...
    location / {
        proxy_cache my_cache;
        proxy_cache_valid 200 60m;
        proxy_cache_valid any 10m;
        ...
    }
}
  • proxy_cache_path: This directive sets the path and parameters for the cache.
  • proxy_cache: This directive enables caching for the specified location.
  • proxy_cache_valid: This directive sets the validity of cached responses. In the above example, responses with a status code of 200 are cached for 60 minutes, and all other responses are cached for 10 minutes.

Use SSL/TLS Encryption

To enable SSL/TLS encryption, you can use the following example:

server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate /path/to/certificate.crt;
    ssl_certificate_key /path/to/certificate.key;
    ...
}
  • listen: This directive specifies the listening port and protocol. In this example, 443 is the HTTPS port.
  • server_name: This directive specifies the hostname that the server responds to.
  • ssl_certificate: This directive specifies the path to the SSL/TLS certificate file.
  • ssl_certificate_key: This directive specifies the path to the SSL/TLS private key file.

These are just a few examples of how you can optimize your Nginx configuration for high traffic websites. There are many other optimizations that you can make, depending on the specific requirements of your website and server environment.

Use HTTP/2

HTTP/2 is a newer version of the HTTP protocol that offers several improvements over HTTP/1.1, such as multiplexing, server push, and header compression. To enable HTTP/2, you can use the following example:

server {
    listen 443 ssl http2;
    ...
}
  • http2: This directive enables HTTP/2 support.

Optimize SSL/TLS Configuration

You can optimize your SSL/TLS configuration by using modern ciphers, disabling insecure protocols, and enabling forward secrecy. Here is an example:

ssl_protocols TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
ssl_dhparam /path/to/dhparam.pem;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8;
  • ssl_protocols: This directive specifies the SSL/TLS protocols to use. In this example, only TLS 1.2 is allowed.
  • ssl_prefer_server_ciphers: This directive tells the server to use its preferred cipher instead of the client’s.
  • ssl_ciphers: This directive sets the list of ciphers to use. The above example specifies a list of strong ciphers that offer perfect forward secrecy (PFS).
  • ssl_dhparam: This directive sets the path to the Diffie-Hellman (DH) parameters file. This is necessary to enable PFS.
  • ssl_session_cache: This directive sets the SSL session cache. The above example uses a shared cache that can hold up to 10 megabytes of data.
  • ssl_session_timeout: This directive sets the maximum time that a session can be cached.
  • ssl_stapling: This directive enables SSL stapling, which allows the server to provide a signed and timestamped OCSP response along with its certificate.
  • ssl_stapling_verify: This directive tells the server to verify the OCSP response from the client.
  • resolver: This directive sets the IP address of the DNS resolver used for OCSP validation.

Use FastCGI Caching

FastCGI caching can be used to cache dynamic content served by FastCGI applications. Here is an example:

fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
server {
    ...
    location / {
        fastcgi_pass unix:/path/to/fastcgi.sock;
        include fastcgi_params;
        fastcgi_cache my_cache;
        fastcgi_cache_valid 200 60m;
        fastcgi_cache_valid any 10m;
        ...
    }
}
  • fastcgi_cache_path: This directive sets the path and parameters for the cache.
  • fastcgi_pass: This directive sets the FastCGI application address.
  • fastcgi_cache: This directive enables caching for the specified location.
  • fastcgi_cache_valid: This directive sets the validity of cached responses. In the above example, responses with a status code of 200 are cached for 60 minutes, and all other responses are cached for 10 minutes.

Tune PHP-FPM settings

PHP-FPM has a number of configuration settings that you can tune to improve performance. These settings are typically found in the php-fpm.conf file or the www.conf file, depending on your installation.

Here are some settings that you might consider tuning:

  • pm.max_children: This setting controls the maximum number of PHP processes that can be run simultaneously. Increasing this value can help handle more concurrent requests, but it also consumes more resources.
  • pm.start_servers: This setting controls the number of PHP processes that are started when PHP-FPM is first launched. Increasing this value can help reduce latency for the first few requests.
  • pm.min_spare_servers and pm.max_spare_servers: These settings control the minimum and maximum number of idle PHP processes that should be kept running to handle incoming requests.
  • pm.max_requests: This setting controls the number of requests that each PHP process can handle before being terminated. This can help prevent memory leaks and other issues.

Use Opcode caching

Opcode caching can significantly improve the performance of PHP by caching the compiled bytecode of PHP scripts, reducing the time it takes to execute them. There are several opcode caching extensions available for PHP, including APCu, OpCache, and XCache.

To use opcode caching with PHP-FPM, you need to configure it in the php.ini file. Here’s an example configuration for OpCache:

[opcache]
opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=10000
opcache.validate_timestamps=0
opcache.revalidate_freq=60
[PHP]
max_execution_time = 60
memory_limit = 512M
post_max_size = 100M
upload_max_filesize = 100M
max_input_vars = 10000
  • opcache.enable: This parameter enables the OpCache extension. Set it to 1 to enable OpCache.
  • opcache.memory_consumption: This parameter sets the amount of memory that OpCache will use to store compiled bytecode. The default value is 64MB, but you may need to increase it depending on the size of your application. In this example, we’ve set it to 256MB.
  • opcache.max_accelerated_files: This parameter sets the maximum number of files that can be stored in the opcode cache. By default, it’s set to 2000, but you may need to increase it if you have a large number of PHP files. In this example, we’ve set it to 10000.
  • opcache.validate_timestamps: This parameter determines whether OpCache will check the timestamps of PHP files to see if they’ve been modified since the last time they were cached. By default, it’s set to 1, which means that OpCache will check the timestamps. However, checking timestamps can be expensive, so it’s recommended to set it to 0 in production environments where files don’t change frequently.
  • opcache.revalidate_freq: This parameter determines how often OpCache will check the timestamps of PHP files when opcache.validate_timestamps is set to 1. The value is in seconds, and the default is 2 seconds. In this example, we’ve set it to 60 seconds, which means that OpCache will check the timestamps once every minute.

Some additional settings that can improve the performance of PHP for a high traffic website.

  • max_execution_time: This setting controls the maximum amount of time (in seconds) that a PHP script can run before being terminated. For a high traffic website, you may want to set this value to 60 or higher, depending on the needs of your application.
  • memory_limit: This setting controls the amount of memory that PHP can use. For a high traffic website, you may want to set this value to 512M or higher, depending on the size and complexity of your application.
  • post_max_size and upload_max_filesize: These settings control the maximum size of POST data and uploaded files, respectively. For a high traffic website that deals with large files or data, you may want to set these values to 100M or higher.
  • max_input_vars: This setting controls the maximum number of input variables that PHP can handle. For a high traffic website that deals with complex forms or input data, you may want to set this value to 10000 or higher.

Again, these values are just examples and may vary depending on your specific needs. It’s important to monitor the performance of your server and adjust the settings accordingly to achieve optimal performance for your high traffic website.

By configuring these parameters, you can optimize the performance of PHP on your Nginx server. Keep in mind that the values used in this example may not be appropriate for all applications, and you should adjust them based on the specific needs of your application.

Conclusion

Optimizing Nginx configuration for high traffic websites is crucial for delivering a smooth and reliable user experience. By tuning settings like server hardware, Nginx configurations, PHP-FPM settings, and Opcode caching, you can improve website performance under heavy traffic. However, there is no one-size-fits-all approach to Nginx configuration optimization, and it is essential to monitor your website’s performance and regularly adjust settings for optimal performance. With the right optimizations and monitoring, you can ensure that your website can handle high traffic volumes and provide a fast and reliable experience to your users.

LEAVE A COMMENT