# Deep Dive on NGINX Directives

NGINX’s flexibility comes from its rich set of configuration directives. In production, understanding these directives can help fine-tune performance, security, and resource management.

***

{% hint style="info" %}
Official list of directives - [NGINX Directive Index](https://nginx.org/en/docs/dirindex.html) with examples and production recommendations.
{% endhint %}

***

## 1. Global and Core Directives

### **worker\_processes**

* **Purpose:** Defines the number of worker processes. , the default value is 1.
* **Example:**

  ```nginx
  worker_processes auto;
  ```
* **Production Tip:**  Use **auto**, as this ensures efficient utilization of system resources to match available CPU cores.

### **error\_log**

* **Purpose:** Specifies the file where errors are logged.
* **Example:**

  ```nginx
  error_log /var/log/nginx/error.log warn;
  ```
* **Default/Recommended:** Default is usually `error.log` in the installation directory; using a log level like `warn` or `error` is ideal for production. Use debug for issues.

### **include**

* **Purpose:** Allows you to include additional configuration files.
* **Example:**

  ```nginx
  include /etc/nginx/conf.d/*.conf;
  ```
* **Production Tip:** Modularize configurations for maintainability.

***

## 2. Events Block Directives

### **worker\_connections**

* **Purpose:** Sets the maximum number of simultaneous connections per worker.
* **Example:**

  ```nginx
  events {
      worker_connections 1024;
  }
  ```
* **Default/Recommended:** Default is often 512 or 1024; adjust based on traffic.
* **Production Tip:** A higher value can help handle heavy loads, but ensure the OS limits are adjusted accordingly.

### **multi\_accept**

* **Purpose:** Allows a worker to accept all new connections at once.
* **Example:**

  ```nginx
  events {
      multi_accept on;
  }
  ```
* **Production Tip:** Helps reduce latency under high connection rates.

***

## 3. HTTP Block Directives

### **include (HTTP Context)**

* **Purpose:** Include MIME types and other HTTP-level configs.
* **Example:**

  ```nginx
  http {
      include mime.types;
      default_type application/octet-stream;
  }
  ```
* **Production Tip:** Keep MIME types updated to ensure proper file delivery.

### **sendfile, tcp\_nodelay, tcp\_nopush**

* **Purpose:** Optimize file transfers.
* **Example:**

  ```nginx
  http {
      sendfile on;
      tcp_nodelay on;
      tcp_nopush on;
  }
  ```
* **Production Tip:** These settings minimize latency and maximize throughput for static files.

### **keepalive\_timeout**

* **Purpose:** Defines the timeout for persistent connections.
* **Example:**

  ```nginx
  http {
      keepalive_timeout 65;
  }
  ```
* **Default/Recommended:** The default is usually 75 seconds; 65 seconds is a common production setting.

### **client\_max\_body\_size**

* **Purpose:** Limits the size of client request bodies.
* **Example:**

  ```nginx
  http {
      client_max_body_size 16M;
  }
  ```
* **Production Tip:** Set a sensible limit based on your application’s needs to mitigate DoS risks.

***

## 4. Server and Location Block Directives

### **listen and server\_name**

* **Purpose:** Bind virtual hosts to specific IPs/ports and domain names.
* **Example:**

  ```nginx
  server {
      listen 80;
      server_name example.com www.example.com;
  }
  ```
* **Production Tip:** Use precise names and ports to avoid ambiguity in multi-tenant environments.

### **root and index**

* **Purpose:** Define where static files are served from.
* **Example:**

  ```nginx
  server {
      root /var/www/html;
      index index.html index.htm;
  }
  ```
* **Production Tip:** Ensure file paths match your deployment structure to prevent 404s.

### **error\_page**

* **Purpose:** Customize responses for error codes.
* **Example:**

  ```nginx
  server {
      error_page 404 /custom_404.html;
      location = /custom_404.html {
          internal;
      }
  }
  ```
* **Production Tip:** Custom error pages enhance user experience and can hide sensitive server information.

***

## 5. URI Processing Directives

### **location**

* **Purpose:** Handle requests based on URI patterns.
* **Example:**

  ```nginx
  server {
      location /static/ {
          root /var/www;
      }
  }
  ```
* **Production Tip:** Combine exact (`location =`), prefix, and regex-based locations carefully to avoid unexpected matches.

### **rewrite**

* **Purpose:** Change request URIs using regex.
* **Example:**

  ```nginx
  server {
      location /old/ {
          rewrite ^/old/(.*)$ /new/$1 permanent;
      }
  }
  ```
* **Production Tip:** Use permanent redirects (`301`) only when URLs have permanently changed.

### **try\_files**

* **Purpose:** Check for the existence of files before proxying or handling errors.
* **Example:**

  ```nginx
  server {
      location / {
          try_files $uri $uri/ /index.html;
      }
  }
  ```
* **Production Tip:** Use `try_files` to efficiently serve static content and reduce backend load.

***

## 6. Proxying and Upstream Directives

### **proxy\_pass**

* **Purpose:** Forward requests to a backend server or upstream group.
* **Example:**

  ```nginx
  server {
      location /api/ {
          proxy_pass http://backend_servers;
      }
  }
  ```
* **Production Tip:** Ensure you correctly forward headers using additional directives (e.g., `proxy_set_header`) for proper client IP logging and security.

### **upstream**

* **Purpose:** Define groups of backend servers for load balancing.
* **Example:**

  ```nginx
  upstream backend_servers {
      server backend1.example.com weight=2;
      server backend2.example.com;
  }
  ```
* **Production Tip:** Configure health checks and use weighted balancing to distribute load evenly.

### **proxy\_set\_header**

* **Purpose:** Modify or add headers when proxying.
* **Example:**

  ```nginx
  location /api/ {
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_pass http://backend_servers;
  }
  ```
* **Production Tip:** Proper header forwarding is crucial for security and logging.

### **proxy\_redirect**

* **Purpose:** Modify the “Location” header in responses from proxied servers.
* **Example:**

  ```nginx
  location /api/ {
      proxy_pass http://backend_servers;
      proxy_redirect off;
  }
  ```
* **Production Tip:** Adjust proxy redirects to maintain client-side URL consistency.

***

## 7. FastCGI, SCGI, and uWSGI Directives

### **fastcgi\_pass and fastcgi\_param**

* **Purpose:** Forward requests to FastCGI application servers.
* **Example:**

  ```nginx
  location ~ \.php$ {
      fastcgi_pass unix:/run/php/php7.4-fpm.sock;
      include fastcgi_params;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  }
  ```
* **Production Tip:** Ensure file paths and socket settings are correct; secure your FastCGI interface to prevent unauthorized access.

***

## 8. Caching and Compression Directives

### **proxy\_cache\_path and proxy\_cache**

* **Purpose:** Configure caching for proxied content.
* **Example:**

  ```nginx
  http {
      proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;
      server {
          location / {
              proxy_cache my_cache;
              proxy_pass http://backend_servers;
          }
      }
  }
  ```
* **Production Tip:** Monitor cache performance and configure proper expiration policies.

### **gzip**

* **Purpose:** Enable response compression.
* **Example:**

  ```nginx
  http {
      gzip on;
          gzip_min_length 1024;
      gzip_types text/plain text/css application/json application/javascript;
  }
  ```
* **Production Tip:** Tweak `gzip_min_length` and `gzip_types` to balance CPU usage and bandwidth savings.

***

## 9. Security and Advanced Directives

### **SSL/TLS Directives**

* **ssl\_certificate and ssl\_certificate\_key**
  * **Purpose:** Define the SSL certificate and key for secure connections.
  * **Example:**

    ```nginx
    server {
        listen 443 ssl;
        ssl_certificate /etc/nginx/ssl/example.com.crt;
        ssl_certificate_key /etc/nginx/ssl/example.com.key;
    }
    ```
  * **Production Tip:** Use automated certificate renewal and strong ciphers.

### **allow and deny**

* **Purpose:** Restrict access based on IP addresses.
* **Example:**

  ```nginx
  location /admin/ {
      allow 192.168.1.0/24;
      deny all;
  }
  ```
* **Production Tip:** Implement IP whitelisting for sensitive resources.

### **auth\_basic**

* **Purpose:** Enable HTTP basic authentication.
* **Example:**

  ```nginx
  location /secure/ {
      auth_basic "Restricted";
      auth_basic_user_file /etc/nginx/.htpasswd;
  }
  ```
* **Production Tip:** For stronger security, integrate with external authentication providers.

### **resolver**

* **Purpose:** Specify DNS servers for resolving domain names (useful for dynamic or upstream configurations).
* **Example:**

  ```nginx
  http {
      resolver 8.8.8.8 8.8.4.4 valid=300s;
      resolver_timeout 5s;
  }
  ```
* **Default/Recommended:** If not set, NGINX falls back to the system resolver. In production, explicitly setting resolvers (for example, Google DNS) improves reliability when using domain names in upstream blocks.
* **Production Tip:** Use a short `resolver_timeout` to avoid delays, and update the DNS list as needed.

### **client\_body\_timeout and client\_header\_timeout**

* **Purpose:** Define timeouts for reading client request bodies and headers.
* **Example:**

  ```nginx
  http {
      client_body_timeout 12;
      client_header_timeout 12;
  }
  ```
* **Production Tip:** Shorten timeouts to mitigate slow client attacks while avoiding premature termination for legitimate users.

***


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wisdom.gitbook.io/gyan/nginx/deep-dive-on-nginx-directives.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
