Configure NGINX.conf

Nginx is a high performance web server that is responsible for handling the load of some of the largest sites on the internet. It is especially good at handling many concurrent connections and excels at serving static content.

While many users are aware of Nginx’s capabilities, new users are often confused by some of the conventions they find in Nginx configuration files. In this guide, we will focus on improving the structure of an Nginx configuration file along with some guidelines on on how to achieve maximum performance.

/etc/nginx/nginx.conf is a file that is included with installations from the NGINX repositories. The file starts with 4 directives: user, worker_processes, error_log, and pid. These are outside any specific block or context, so they’re said to exist in the main context. The events and http blocks are areas for additional directives, and they also exist in the main context.

worker_processes auto;

      The optimal value depends on many factors including (but not limited to) the number of CPU cores, the number of hard disk drives that store data, and load pattern. When one is in doubt, setting it to the number of available CPU cores would be a good start.

(the value “auto” will try to autodetect it).

pcre_jit on;

    Enables or disables the use of “just-in-time compilation” (PCRE JIT) for the regular expressions known by the time of configuration parsing. PCRE JIT can speed up processing of regular expressions significantly.

Event directive {

nginx supports a variety of connection processing methods. The availability of a particular method depends on the platform used. On platforms that support several methods, nginx will normally select the most efficient method automatically. However, if needed, a connection processing method can be selected explicitly with the “event” directive.

accept_mutex off;

    If accept_mutex is enabled, specifies the maximum time during which a worker process will try to restart accepting new connections if another worker process is currently accepting new connections. (should be disabled if you use reuseport or epoll)

worker_connections 8192;

    Sets the maximum number of simultaneous connections that can be opened by a worker process. (also includes requests to proxy servers, services and applications, we recommend 8192 or higher for production servers.)

multi_accept on;

    If multi_accept is disabled, a worker process will accept one new connection at a time. Otherwise, a worker process will accept all new connections at a time.

use epoll; OR use kqueue;

    Nginx supports a lot of connection processing methods. The most used for modern kernels (2.6.x) is epoll to get the best performance while processing information. Use kqueue method for FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0, and macOS.

}

HTTP directive {

The http block contains directives for handling web traffic. These directives are often referred to as universal because they are passed on to all website configurations NGINX serves. See the NGINX docs for a list of available directives for the http block.

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=myCache:8m max_size=100m inactive=1h;

    nginx will keep all active keys and information about data are stored in a shared memory zone, whose name and size are configured by the keys_zone parameter. if a page was cached, it consults shared memory first.

absolute_redirect on;

    If disabled, redirects issued by nginx will be relative.

aio on;

    Enables or disables the use of asynchronous file I/O (AIO) on FreeBSD and Linux. For best performance (nginx 1.7.11+) files can be read and sent using multi-threading, without blocking a worker process, change on; to threads;

client_body_timeout 10s;

    Defines a timeout for reading client request body. The timeout is set only for a period between two successive read operations, not for the transmission of the whole request body. If a client does not transmit anything within this time, the request is terminated with the 408 (Request Time-out) error. (default 60s)

client_header_timeout 10s;

    Defines a timeout for reading client request header. If a client does not transmit the entire header within this time, the request is terminated with the 408 (Request Time-out) error. (default 60s)

connection_pool_size 256|512;

    Allows accurate tuning of per-connection memory allocations. This directive has minimal impact on performance and should not generally be used. By default, the size is equal to 256 bytes on 32-bit platforms and 512 bytes on 64-bit platforms.

etag on;

    Enables or disables automatic generation of the “ETag” response header field for static resources.

ignore_invalid_headers on;

    Controls whether header fields with invalid names should be ignored. Valid names are composed of English letters, digits, hyphens, and possibly underscores (as controlled by the underscores_in_headers directive).

keepalive_requests 1024;

    Sets the maximum number of requests that can be served through one keep-alive connection. After the maximum number of requests are made, the connection is closed. (default 100)

keeplive_timeout 5;

    The first parameter sets a timeout during which a keep-alive client connection will stay open on the server side. The zero value disables keep-alive client connections. Reduce to close unnecessary and inactive connections faster (default 75)

lingering_time 10s;

    This directive specifies the maximum time during which nginx will process (read and ignore) additional data coming from a client. After that, the connection will be closed, even if there will be more data. (default 30s)

open_file_cache max=1024 inactive=60s;

    Configures a cache that can store:
    open file descriptors, their sizes and modification times, information on existence of directories and file lookup errors, such as “file not found”, “no read permission”, etc.

open_file_cache_min_uses 3;

    Sets the minimum number of file accesses during the period configured by the inactive parameter of the open_file_cache directive, required for a file descriptor to remain open in the cache.

open_file_cache_valid 180s;

    Sets a time after which open_file_cache elements should be validated.

output_buffers 2 32k;

    Sets the number and size of the buffers used for reading a response from a disk.

read_ahead 0;

    (Linux) Sets the amount of pre-reading for the kernel when working with file.

request_pool_size 4k;

    Allows accurate tuning of per-request memory allocations. This directive has minimal impact on performance and should not generally be used.

reset_timedout_connection on;

    When a client connection times out, its associated information may remain in memory depending on the state it was on. Enabling this directive will erase all memory associated with the connection after it times out. This helps avoid keeping an already closed socket with filled buffers in a FIN_WAIT1 state for a long time.

sendfile on;

    If this directive is enabled, Nginx will use the sendfile kernel call to handle file transmission. If disabled, Nginx will handle the file transfer by itself. Depending on the physical location of the file being transmitted (such as NFS), this option may affect the server performance. Test what’s best for your workspace.

sendfile_max_chunk 0;

    When set to a non-zero value, limits the amount of data that can be transferred in a single sendfile() call. Without the limit, one fast connection may seize the worker process entirely.

server_names_hash_bucket_size 32|64|128;

    Sets the bucket size for the server names hash tables. The default value depends on the size of the processor’s cache line. The details of setting up hash tables are provided in a separate document.

server_names_hash_max_size 512;

    Nginx uses hash tables for various data collections in order to speed up the processing of requests. This directive defines the maximum size of the server names hash table. The default value should fit with most configurations. If this needs to be changed, Nginx will automatically tell you on startup, or when you reload its configuration.

server_tokens on|off;

    This directive allows you to define whether or not Nginx should inform clients of the running version number.

subrequest_output_buffer_size 4k|8k;

    Sets the size of the buffer used for storing the response body of a subrequest. By default, the buffer size is equal to one memory page. This is either 4K or 8K, depending on a platform. It can be made smaller, however.

tcp_nodelay on;

    Enables or disables the use of the TCP_NODELAY option. The option is enabled when a connection is transitioned into the keep-alive state. Additionally, it is enabled on SSL connections, for unbuffered proxying, and for WebSocket proxying.

tcp_nopush on;

    Enables or disables the TCP_NOPUSH (FreeBSD) or TCP_CORK (Linux) socket option. Note that this option only applies if the sendfile directive is enabled. If tcp_nopush is set to on, Nginx will attempt to transmit the entire HTTP response headers in a single TCP packet.

types_hash_bucket_size 64;

    Sets the bucket size for the MIME types hash tables. You should only change this value if Nginx tells you to. (default 64)

fastcgi_ignore_headers X-Accel-Expires Expires Cache-Control;

    This directive prevents Nginx from processing one or more of the following headers from the backend server response: X-Accel-Redirect X-Accel-Expires Expires Cache-Control X-Accel-Limit-Rate X-Accel-Buffering X-Accel-Charset

fastcgi_connect_timeout 30s;

    This directive defines the backend server connection timeout. This is different than the read/send timeout. If Nginx is already connected to the backend server, the fastcgi_connect_timeout is not applicable. (default 60s)

fastcgi_send_timeout 30;

    The timeout for sending data to the backend server. The timeout isn’t applied to the entire response delay but rather between two write operations. (default 60s)

fastcgi_read_timeout 30;

    Defines the timeout for the response from the FastCGI application. If Nginx does not receive the response after this period, the 504 Gateway Timeout HTTP error is returned. (default 60s)

fastcgi_keep_conn on;

    When set to on, Nginx will conserve the connection to the FastCGI server, thus reducing overhead.

fastcgi_force_ranges on;

    When set to on, Nginx will enable byte-range support on responses from the FastCGI backend.

fastcgi_cache yourname;

    Defines a cache zone. The identifier given to the zone is to be reused in further directives. You can change “yourname” to whatever you like, make sure you update the cache_path too under “keys_zone=yourname”.

fastcgi_cache_path /tmp/cache levels=1:2 keys_zone=yourname:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";

    Indicates the directory for storing cached files, as well as other parameters.

fastcgi_cache_min_uses 3;

    Sets the number of requests after which the response will be cached.

fastcgi_cache_valid 200 301 302 1440m;

    Sets cache for responses on header, 200/OK, 301/moved, 302/redirected.

fastcgi_cache_bypass $cookie_bypass_cache;

    Tells nginx whether or not the request should be loaded from cache. (You want to bypass on cookies)

fastcgi_buffering on;

    • Enables or disables buffering of responses from the FastCGI server.
    When buffering is enabled, nginx receives a response from the FastCGI server as soon as possible, saving it into the buffers set by the fastcgi_buffer_size and fastcgi_buffers directives. If the whole response does not fit into memory, a part of it can be saved to a temporary file on the disk. Writing to temporary files is controlled by the fastcgi_max_temp_file_size and fastcgi_temp_file_write_size directives.

fastcgi_buffers 8 4k;

    sets the number and size of buffers that will be used for reading the response data from the FastCGI application.

fastcgi_buffer_size 4k;

    This directive sets the size of the buffer for reading the beginning of the response from the FastCGI application, which usually contains simple header data. Value corresponds to the size of one buffer.

fastcgi_cache_revalidate off;

    When disabled, nginx doesn’t revalidate expired cache items when instructed to do so by the If-modified-since and If-none-match headers.

http2_push_preload on;

    Enables automatic conversion of preload links specified in the “Link” response header fields into push requests.

http2_push /static/css/main.css;

    • Server push lets the server preemptively “push” website assets to the client without the user having explicitly asked for them. Use this with essential static files that needs to load on every page. change the

/static/css/main.css

    to your file path.

http2_recv_timeout 30s;

    Sets the timeout for expecting more data from the client, after which the connection is closed.

http2_max_requests 1000;

    • Sets the maximum number of requests (including push requests) that can be served through one HTTP/2 connection, after which the next client request will lead to connection closing and the need of establishing a new connection.

Closing connections periodically is necessary to free per-connection memory allocations. Therefore, using too high maximum number of requests could result in excessive memory usage and not recommended.

http2_idle_timeout 1m;

    Sets the timeout of inactivity after which the connection is closed.

proxy_cache_valid 200 301 302 60m;

    This directive allows you to customize the caching time for different kinds of response codes. You may cache responses associated with 404 error codes for 1 minute, and on the opposite cache, 200 OK responses for 10 minutes or more.

proxy_cache_use_stale off;

    Defines whether or not Nginx should serve stale cached data in certain circumstances (in regard to the gateway). If you use proxy_cache_use_stale timeout, and if the gateway times out, then Nginx will serve cached data.

proxy_buffer_size 8k;

    Sets the size of the buffer for reading the beginning of the response from the backend server, which usually contains simple header data.

proxy_buffers 8 4k;

    Sets the amount and size of buffers that will be used for reading the response data from the backend server.

proxy_cache cache_1;

    Defines a cache zone. The identifier given to the zone is to be reused in further directives.

proxy_cache_convert_head on;

    Enables or disables the conversion of the “HEAD” method to “GET” for caching. When the conversion is disabled, the cache key should be configured to include the $request_method.

proxy_cache_key $scheme$proxy_host$request_uri$args$uri;

    Defines a key for caching

proxy_cache_bypass $cookie_bypass_cache;

    Proxy cache bypasses on cookie requests.

proxy_headers_hash_bucket_size 32;
proxy_headers_hash_max_size 256;

    Sets the bucket size for the proxy header’s hash tables and the maximum size for the proxy header’s hash tables.

proxy_http_version 1.1;

    Sets the HTTP version to be used for communicating with the proxy backend. HTTP 1.0 is the default value, but if you are going to enable keepalive connections, you might want to set this directive to 1.1.

proxy_cache_min_uses 1;

    Defines the minimum amount of hits before a request is eligible for caching. By default, the response of a request is cached after one hit (next requests with the same cache key will receive the cached response).

proxy_ssl_protocols TLSv1.2 TLSv1.3;

    Sets the proxy’s SSL protocols. For modern browser we recommend TLSv1.2 and TLSv1.3 if your server supports it.

proxy_ssl_session_reuse on;

    Reuses SSL session, so proxy does not have to re-communicate.

}

Apply settings to nginx.

When you’ve added variable(s) trough the configuration file, intent to access your server by SSH and execute the following command: nginx -t

If everything is set correctly, you’ll get the following output:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok.
nginx: configuration file /etc/nginx/nginx.conf is successfull.

Finally, enter: service nginx restart to gracefully restart the nginx server. All configs are now active.

In other cases, you may have made a typo or added a unsupported/incompatible variable. Nginx will tell you so by the following error code:

Job for nginx.service failed because the control process exited with error code.
See “systemctl status nginx.service” and “journalctl -xe” for details.

As mentioned, type the systemctl status nginx.service command to view the error log, and correct it accordingly. Restart nginx server, and you’r all set.

You can also simply restart the server itself by reboot command. It is worth mentioning that if you have a error in the configuration, restarting the server will not fix this.

Add comment

Why do you Optimize?

Loading ... Loading ...

Did you know?

Every > 1s delay in page load decreases conversion by 11%

According to Google:
“speed equals revenue”

40% of people abandon a website that takes more than > 3s to load.

PageSpeed can have direct impacts on your Adwords campaigns

As page time goes from 1s > 5s probability of bounce increases by 90%