Nginx Configuration Made Easy 1

Nginx Configuration Made Easy- 14 Detailed Tips for Success

Configuring Nginx, the popular web server and reverse proxy, plays a crucial role in optimizing website performance and security. However, it can be a complex task that requires careful attention to detail. In this guide, we present you with valuable Nginx configuration tips to help you achieve the best Nginx performance. Whether you’re a seasoned system administrator or a beginner exploring web server administration, these tips will furnish you with ideas to enhance the efficiency, reliability, and scalability of your Nginx setup.

Nginx is a high-performance web server that’s especially good at handling large numbers of concurrent connections. It has the ability to process many requests at the same time, and even if one request is taking several seconds to complete, other requests can be processed concurrently. Nginx also uses fewer system resources than some other servers, which allows it to handle more traffic without incurring performance penalties.

Nginx Configuration Made Easy 2

Nginx Memory allocation

One of the most important aspects of Nginx configuration is memory allocation. The more RAM you have, the more you can allocate to Nginx and the faster it will be able to serve requests.  The minimum amount of RAM required for Nginx largely depends on the specific configuration and the expected workload. Generally, Nginx itself is known to be lightweight and can run efficiently even on systems with limited resources. In many cases, Nginx can operate smoothly with as little as 32 megabytes of RAM. However, the actual memory requirements will vary based on factors such as the number of worker processes, the size of the configuration, and the concurrent connections it needs to handle.

You can increase default memory allocation by changing the worker_processes directive in your Nginx configuration file.

Open the Nginx configuration file for editing. The location of the file may vary depending on your operating system and installation method. The default path is often /etc/nginx/nginx.conf or /etc/nginx/conf.d/default.conf.

Inside the configuration file, locate the HTTP block, which contains the main configuration settings for Nginx.

Add or modify the worker_processes directive to specify the desired number of worker processes. For example, if you want to increase the number of worker processes to 50, you can set it as follows:

worker_processes 50;

Save the configuration file and exit the editor.

After saving your changes, press Control+X to exit the editor. Once you’ve made any changes to your Nginx configuration file, be sure to run the following command to test the new configuration.

nginx -t

If all is good, Restart the Nginx using the appropriate command to apply the changes.

sudo service nginx restart  

sudo systemctl restart nginx

sudo systemctl restart nginx

Above setup will tell Nginx to use 50 worker processes. With typical worker process usage of 5 MB per worker, this shall consume around 250M megabytes. This figure is just a guide, not a precise number, actual memory allocation will depend on your system config.

 

Nginx Configuration Made Easy 5

Nginx Server block configuration

Nginx’s server block configuration is one of the most important parts to get right in order to make sure your website is as fast and secure as possible.

The first step is deciding how you wish to host your site or sites. If it’s just one website, then a single server block will be fine. But if you have subdomains (example: www), then you’ll need more than one server block.

To configure Nginx for a single site, add this code:

server

{

listen 80;

server_name example.com;

location / { proxy_pass http://127.0.0.1:8080; }

 }

 To configure Nginx for multiple sites, add this code:

server {

    listen 80;

    server_name exampleone.com;

     # domain config such as Webroot etc

    # …

}

 server {

    listen 80;

    server_name exampletwo.com;

 # domain config such as Webroot etc   

# …

}

Nginx – Setup SSL configuration

We are assuming that you can purchase an SSL certificate from a trusted certificate authority (CA) or obtain a free SSL certificate from Let’s Encrypt. The SSL certificate typically consists of a public key certificate file and a private key file. Now to configure Nginx:

Open the Nginx configuration file for editing. The location of the file may vary, but it’s commonly found at /etc/nginx/nginx.conf

/etc/nginx/conf.d/default.conf.

Inside the http block, add a new server block for your domain with the appropriate configuration. For example:

server {

    listen 80;

    server_name example.com;

    return 301 https://$host$request_uri;

}

 server {

    listen 443 ssl;

    server_name example.com;

       ssl_certificate /path/to/ssl_certificate.crt;

    ssl_certificate_key /path/to/ssl_private_key.key;

       # Other SSL-related configurations

    # …

}

In the above example, the first server block redirects HTTP traffic to HTTPS by issuing a 301 redirect. The second server block listens on port 443 for HTTPS connections, specifies the SSL certificate and private key file paths, and allows you to configure other SSL-related settings.

See also  Web Content Management Systems-Features and Benefits

 

Enable SSL-related Modules:

Ensure that the necessary modules for SSL are enabled in your Nginx installation. Common modules include

ngx_http_ssl_module

ngx_stream_ssl_module

You can check if these modules are enabled by running the command nginx -V and examining the output. If the modules are missing, you may need to recompile Nginx with the necessary modules or install a package that includes SSL support.

Verify the Nginx configuration for syntax errors by running the command: nginx -t.

Visit your website using https://example.com in a web browser to verify that SSL is working correctly.

Nginx Server block configuration – Simple www to non-www Redirect

Open the Nginx configuration file for editing. The location of the file may vary, but it’s commonly found at /etc/nginx/nginx.conf or /etc/nginx/conf.d/default.conf.

Inside the http block, locate the server block that corresponds to your domain. It should include a server_name directive specifying your domain. For example:

server {

    listen 80;

    server_name example.com;

       # Configuration for example.com

    # …

}

inside the server block, add a new server block to handle requests with the www prefix. This block will perform the redirection. For example:

server {

    listen 80;

    server_name www.example.com;

    return 301 $scheme://example.com$request_uri;

}

In the above example, the new server block listens for requests with the www.example.com domain and issues a 301 redirect to the non-www version (example.com) using the same scheme (http or https) and the requested URI.

Save the configuration file and exit the editor, Test the Nginx configuration

Setup Nginx as Reverse Proxy servers

Nginx is a reverse proxy server, and it can be used as a reverse proxy server to load and balance traffic between multiple web servers. The most common use case is when you have multiple web servers that are serving the same content, but they need to be load balanced because one or more of them may fail at any point in time.

Nginx Domain name setup

The first step is to configure your domain name. This can be done by adding the following to the config file :

server {

    listen 80;

    server_name example.com;

       location / {

        proxy_pass http://backend_server;

        proxy_set_header Host $host;

        # Additional proxy settings if needed

        # …

    }

}

Always test the server configuration after any modifications, as described earlier.

Error Log files

  • The error log files are located in /var/log/nginx.
  • They are rotated daily, based on size and number of logs.

The error log files are usually kept in the below location:

/var/log/nginx,

If you want to set up your own error log file area, edit the nginx config file and follow the directions below

server {

    listen 80;

    server_name example.com;

    error_log /var/log/nginx/error.log;

    # Other server configurations

    # …

}

 Always test the new config by running the command

nginx -t

Cache setup

Nginx uses a memory cache to keep frequently accessed objects in memory. This way, Nginx can serve content faster to clients than it would if it had to retrieve the same content from storage each time.

To setup the cache, edit the nginx config file in your preferred editor

server {

    listen 80;

    server_name example.com;

       proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mycache:10m max_size=10g inactive=60m;

    proxy_cache mycache;

    proxy_cache_valid 200 302 30m;

    proxy_cache_valid 404 10m;

       location / {

        proxy_pass http://backend_server;

        proxy_set_header Host $host;

           # Additional proxy settings if needed

        # …

    }

}

The proxy_cache_path directive specifies the path where the cache files will be stored, the maximum size of the cache (max_size), and other parameters like inactive time.

The proxy_cache directive enables the caching using the defined cache zone (mycache in this case).

The proxy_cache_valid directive sets the caching duration for different HTTP response codes. In this example, responses with a status code of 200 or 302 will be cached for 10 minutes, while 404 responses will be cached for 1 minute.

Gzip Compression

Gzip compression is one of the best ways to improve your website’s speed. It compresses files before they are sent to your users, which reduces the amount of data they need to download. To enable and configure gzip compression in your nginx server, edit the config file in your preferred editor.

See also  The Right Hosting-Shared vs. Dedicated-Pros and Cons

server {

listen 80;

server_name example.com;

 gzip on;

gzip_comp_level 4;

gzip_min_length 1100;

gzip_proxied any; # gzip off for static files like images and CSS

gzip_vary on;

gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/*+xml ;

 }

The gzip on; directive enables gzip compression.

The gzip_types directive specifies the MIME types to be compressed. Only responses with these content types will be compressed. Modify the list of types based on your specific requirements.

The gzip_min_length directive sets the minimum length in bytes of a response that will be compressed. Responses smaller than this length will not be compressed.

The gzip_comp_level directive sets the compression level. A higher value results in better compression but consumes more CPU resources.

The gzip_proxied directive configures how Nginx handles requests coming from a proxy server.

The gzip_vary directive adds the “Vary: Accept-Encoding” header to indicate to clients that the content is compressed. This helps with caching.

Nginx Configuration Made Easy 3

Max file size & types for uploads

When you’re uploading files to your server, you want to make sure that the files are within a reasonable size. This is because if they are too large, it can cause problems with your website.

To set up maximum file size, maximum upload size, and allowed file types in Nginx, you can use a combination of client_max_body_size, client_body_temp_path, and HTTP and server block directives.

Open the Nginx configuration file for editing.

Inside the http block, add the following directive to set the temporary path for storing client request bodies:

http {

    …

    client_body_temp_path /path/to/temporary/directory;

    …

}

Inside the server block where you want to set the maximum file size, maximum upload size, and allowed file types, add the following directives:

server {

    …

    client_max_body_size 100m;

    client_body_buffer_size 128k;

    client_body_temp_path /path/to/temporary/directory;

    client_body_in_file_only clean;

     location /upload {

        client_body_in_file_limit 10m;

        client_body_in_single_buffer on;

        client_body_timeout 60s;

        client_max_body_size 100m;

        client_body_buffer_size 128k;

         proxy_pass http://backend_server;

        proxy_set_header Host $host;

        …

    }

client_max_body_size sets the maximum size of the client request body, including file uploads. Modify the size (100m in this example) according to your needs.

client_body_buffer_size sets the size of the buffer used for reading the client request body.

client_body_temp_path specifies the temporary path for storing the client request bodies.

client_body_in_file_only ensures that the client request bodies are only stored in files and not kept in memory.

Inside the location /upload block, additional directives are set specifically for the upload endpoint. You can adjust these values based on your requirements.

Nginx Capacity to Redirects & rewrites

Nginx allows you to set up simple redirects using the return directive or the rewrite directive. Here’s an overview of both methods along with an example for each:

Using the return directive:

The return directive is a simple way to perform redirects in Nginx by specifying the HTTP status code and the target URL.

server {

    listen 80;

    server_name example.com;

       location /old-page {

        return 301 http://example.com/new-page;

    }

       # Other server configurations

    # …

}

 

In the above example, any request to /old-page will be redirected with a 301 status code to http://example.com/new-page.

Using the rewrite directive:

The rewrite directive provides more flexibility by allowing pattern matching and rewriting of URLs.

server {

    listen 80;

    server_name example.com;

       location /old-page {

        rewrite ^/old-page$ http://example.com/new-page permanent;

    }

   

    # Other server configurations

    # …

}

 In the above example, a request to /old-page will be matched using the regular expression ^/old-page$ and permanently redirected to http://example.com/new-page.

Redirecting to HTTPS:

To redirect HTTP requests to HTTPS, you can use the return directive with a 301 status code and the HTTPS URL.

server {

    listen 80;

    server_name example.com;

       location / {

        return 301 https://example.com$request_uri;

    }

       # Other server configurations

    # …

}

Nginx Configuration Made Easy 6

Nginx Regex setup

Nginx Regex is used to match a string of text with a regular expression. In Nginx, regular expressions (regex) are powerful pattern-matching tools used to match and manipulate strings. Nginx uses the PCRE (Perl Compatible Regular Expressions) library for regex support. Regular expressions in Nginx are mainly used for location matching and rewriting URLs. Here’s an overview of regex expressions in Nginx along with an example:

A quick note on Regex Operators and Modifiers:

See also  Unleash Your Website's Potential-Best Web Performance Test Tools

~ indicates a case-sensitive match.

~* indicates a case-insensitive match.

. matches any single character.

* matches zero or more occurrences of the previous character or group.

+ matches one or more occurrences of the previous character or group.

? matches zero or one occurrence of the previous character or group.

^ matches the beginning of a string.

$ matches the end of a string.

[] specifies a character range.

() creates a capturing group.

server {

    listen 80;

    server_name example.com;

     location ~ ^/book/(\d+)/?$ {

        # Regex capturing group is used to extract the book ID

        rewrite ^/book/(\d+)/?$ /book?id=$1 last;

    }

     # Other server configurations

   # …

}

In the above example, the regex pattern ^/book/(\d+)/?$ matches URLs starting with /articles/ followed by one or more digits, optionally ending with a trailing slash. The capturing group (\d+) captures the digits as the article ID. The rewrite directive then rewrites the URL to /book?id=$1, where $1 represents the captured  ID. For example, /book/123 will be rewritten to /book?id=123.

Nginx denial of service security setup

Nginx offers various methods to mitigate denial-of-service (DoS) attacks and ensure the availability and stability of your server. Here are a few key denial-of-service mitigation techniques commonly used with Nginx:

Rate Limiting:

Nginx’s limit_req and limit_conn modules enable rate limiting to control the number of requests per second or the number of simultaneous connections from a single IP address or a group of IP addresses.

Rate limiting can help prevent excessive resource consumption and mitigate DoS attacks by limiting the request or connection rate.

Connection and Request Limiting:

Nginx allows you to set connection and request limits using directives such as worker_connections, worker_rlimit_nofile, and limit_req_zone.

These directives control the maximum number of simultaneous connections and open file descriptors that Nginx can handle, ensuring that the server’s resources are not overwhelmed.

IP Whitelisting and Blacklisting:

Nginx’s access module allows you to specify IP-based access rules using the allow and deny directives.

By configuring IP whitelists and blacklists, you can restrict access to your server, blocking suspicious or malicious IP addresses from reaching your application.

Security Modules:

Nginx provides additional security modules such as ModSecurity and NAXSI, which offer extensive rule sets and heuristics to detect and block malicious requests.

Load Balancing and Scaling:

By implementing load balancing with Nginx, you distribute incoming requests across multiple backend servers, improving the overall availability and handling capacity of your infrastructure.

Scaling your infrastructure horizontally by adding more backend servers can help handle increased traffic and mitigate the impact of DoS attacks.

Serving static files with Nginx

Serving static files with Nginx is a common use case and can greatly improve the performance and efficiency of delivering static content. Here’s a step-by-step guide on how to serve static files using Nginx:

Open the Nginx configuration file for editing

Inside the http block, locate or create a server block where you want to serve the static files.

Within the server block, add a location block to specify the URL path for serving the static files and define the configuration for serving those files. For example:

server {

    listen 80;

    server_name example.com;

     location /static {

        alias /path/to/static/files;

        expires max;

    }

     # Other server configurations

    # …

}

 In the above example, the location /static block is configured to serve static files from the /path/to/static/files directory. The alias directive specifies the actual file system path where the static files are located. The expires directive sets the caching header to ensure client-side caching for maximum efficiency.

Nginx Configuration Made Easy 4

Setup an error 404 page in Nginx

To serve a custom 404 page in Nginx, you can follow these steps:

Create a custom HTML file for your 404 page. You can name it 404.html or any other suitable name. Make sure the file is located in a directory accessible by Nginx.

Open the Nginx configuration file for editing.

Inside the http block, locate or create a server block where you want to configure the 404 page.

Within the server block, add the following error_page directive to specify the location of the custom 404 page:

server {

    listen 80;

    server_name example.com;

     # Other server configurations

     error_page 404 /404.html;

     # Other server configurations

    # …

}

In the above example, the error_page directive specifies that when Nginx encounters a 404 error, it should serve the /404.html page.

Alternatively, you can also specify an external URL or redirect to another location using a different server block or rewrite directive.