Skip to main content

Working with Nginx Modules

1. Understanding Core Modules

Module Description Directive Default
core Basic HTTP server functionality http Enabled
events Event handling (e.g., worker_connections) events Enabled
http HTTP server and proxy module http Enabled
stream TCP/UDP load balancing and proxying stream Disabled

Example: Basic HTTP module configuration

http {
    server {
        listen 80;
        root /var/www;
        index index.html;
    }
}

2. Using ngx_http_rewrite_module

Directive Description Example
rewrite Performs a rewrite based on the specified regex pattern and replacement. rewrite ^/old-path/(.*)$ /new-path/$1 permanent;
rewrite_log Enables or disables logging of rewrite operations. rewrite_log on;
if Conditionally applies directives based on a specified condition.
if ($request_uri ~* "\.php$") {
    return 403;
}
Note: The rewrite directive is processed in the order it appears in the configuration file.
Warning: Avoid using rewrite in a loop as it can lead to infinite loops.

Common Use Cases

  • URL redirections
  • SEO-friendly URLs
  • Access control based on URL patterns

3. Using ngx_http_ssl_module

Directive Values Description
ssl on | off Enables or disables SSL for the server block.
ssl_certificate /path/to/cert.pem Specifies the path to the SSL certificate file.
ssl_certificate_key /path/to/key.pem Specifies the path to the private key file.
ssl_protocols SSLv3, TLSv1, TLSv1.1, TLSv1.2, TLSv1.3 Enables or disables specific SSL/TLS protocols.
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDH-RSA-AES256-GCM-SHA512 Defines the list of ciphers to use for SSL connections.
ssl_prefer_server_ciphers on | off Enables or disables preference for server ciphers over client ciphers.

Example: Basic SSL Configuration

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDH-RSA-AES256-GCM-SHA512;
    ssl_prefer_server_ciphers on;

    location / {
        root /var/www/html;
        index index.html;
    }
}
Note: Ensure that the certificate and key files have appropriate permissions to be read by the Nginx process.

4. Using ngx_http_gzip_module

Directive Values Description
gzip on | off Enables or disables gzip compression for responses.
gzip_types Content-Type values Defines MIME types to compress. Default includes text/html.
gzip_min_length Integer (bytes) Minimum response size to compress. Default is 20 bytes.
gzip_comp_level 1-9 Compression level (1 = fastest, 9 = best compression). Default is 1.

Example: Basic gzip configuration

server {
    listen 80;
    root /var/www;

    gzip on;
    gzip_types text/plain text/css application/json application/javascript;
    gzip_min_length 1024;
    gzip_comp_level 5;
}
Note: Gzip compression is most effective for text-based content like HTML, CSS, JS, and JSON. Binary files are not compressed.

5. Using ngx_http_proxy_module

Directive Values Description
proxy_pass http://backend Specifies the address of the proxied server
proxy_set_header Host $host Sets a header to be passed to the proxied server
proxy_connect_timeout 5s Timeout for connecting to the proxied server
proxy_send_timeout 60s Timeout for sending a request to the proxied server
proxy_read_timeout 60s Timeout for reading a response from the proxied server

Example: Basic proxy configuration

location /api/ {
    proxy_pass http://backend;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

Example: Proxy with timeout settings

location /service/ {
    proxy_pass http://internal.service;
    proxy_connect_timeout 10s;
    proxy_send_timeout 30s;
    proxy_read_timeout 30s;
}

6. Using ngx_http_fastcgi_module

Directive Values Description
fastcgi_pass address Specifies the FastCGI server address, which can be a domain name, IP address with port, or Unix socket path.
fastcgi_param parameter value Sets a parameter to be passed to the FastCGI server. Can include variables.
fastcgi_index index_file Defines the default index file to be used when a directory is requested.
fastcgi_read_timeout time Defines the timeout for reading a response from the FastCGI server.
fastcgi_connect_timeout time Defines the timeout for connecting to the FastCGI server.

Example: Basic FastCGI Configuration

location /php/ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param QUERY_STRING $query_string;
    fastcgi_read_timeout 300;
}
Note: The fastcgi_param directive is used to pass variables to the FastCGI server. Common parameters include SCRIPT_FILENAME, QUERY_STRING, and REQUEST_METHOD.
Warning: Ensure that the FastCGI server (e.g., PHP-FPM) is running and accessible at the specified address. Misconfiguration can lead to 502 Bad Gateway errors.

7. Using ngx_http_auth_basic_module

Directive Values Description
auth_basic on | off | string Enables or disables basic authentication. Set to a string to define the realm name.
auth_basic_user_file file-path Specifies the file containing user credentials in the htpasswd format.

Example: Basic Authentication Setup

server {
    listen 80;
    server_name example.com;

    location /admin {
        auth_basic "Admin Area";
        auth_basic_user_file /etc/nginx/htpasswd;
    }
}
Note: The htpasswd file must be created using the htpasswd utility or manually formatted.

Example: Creating htpasswd File

htpasswd -c /etc/nginx/htpasswd admin
# Output:
# New password:
# Re-type new password:
# Adding password for user admin

8. Using ngx_http_access_module

Directive Values Description
allow IP | CIDR Allows access from specified IP address or network range
deny IP | CIDR Denies access from specified IP address or network range
satisfy all | any Determines how to handle multiple access control directives; all requires all rules to match, any allows access if any rule matches

Example: Basic IP Allow/Deny Rules

location /admin {
    allow 192.168.1.0/24;
    allow 10.0.0.0/8;
    deny all;
}

Example: Using satisfy any

location / {
    satisfy any;
    allow 192.168.1.0/24;
    allow 10.0.0.0/8;
    deny 192.168.1.100;
}

9. Loading Dynamic Modules

Directive Values Description
load_module modules/ngx_http_geoip_module.so Loads a dynamic module at startup. Must be placed before any http, stream, or mail context.

Example: Loading a Dynamic Module

load_module modules/ngx_http_geoip_module.so;

events {
    worker_connections 1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    server {
        listen 80;
        server_name example.com;

        location / {
            geoip_country country;
            root /var/www;
        }
    }
}
Note: Dynamic modules must be compiled with the same version of Nginx to ensure compatibility.
Warning: Loading modules at runtime is not supported in Nginx. All load_module directives must be present in the configuration file before Nginx starts.

10. Compiling Third-party Modules

Compiling third-party Nginx modules requires a few steps to ensure compatibility and proper integration with your Nginx installation.

Example: Compiling a Third-party Module

cd /usr/src/nginx-1.25.3
./configure --with-http_ssl_module --add-module=/path/to/third-party-module
make
make install
Step Description Notes
Download Source Obtain the Nginx source code matching your installed version. Ensure version compatibility to avoid build errors.
Configure with Module Use --add-module to specify the module path. Module must be compiled with same Nginx version.
Compile Run make to compile the modified Nginx binary. Use make install to replace the existing binary.
Note: Ensure that the third-party module is compatible with your Nginx version and that all dependencies are met before compiling.

11. Using ngx_http_realip_module

Directive Values Description
set_real_ip_from 192.168.1.0/24 Defines trusted proxy IP addresses or networks that can set the real client IP
real_ip_header X-Forwarded-For Specifies the HTTP header from which to get the real IP address
real_ip_recursive on Enables recursive processing of headers to find the real IP address

Example: Configuring real IP handling

server {
    listen 80;
    server_name example.com;

    set_real_ip_from 192.168.1.0/24;
    real_ip_header X-Forwarded-For;
    real_ip_recursive on;

    location / {
        proxy_pass http://backend;
    }
}
Note: The ngx_http_realip_module is not part of the standard Nginx distribution and must be compiled in or installed separately.

12. Using ngx_http_stub_status_module

The ngx_http_stub_status_module module provides a way to get basic status information about the Nginx server, including connection counts, request rates, and processing times. It is often used for monitoring and performance analysis.

Directive Values Description
stub_status on | off Enables or disables the status page. Default is off.

Example: Enabling stub_status

location /nginx_status {
    stub_status on;
    access_log off;
    allow 127.0.0.1;
    deny all;
}
Note: The status page is typically accessed via a dedicated location block and should be protected to prevent unauthorized access.

Sample Output

The output of the stub status page includes the following fields:

Field Description
Active connections Number of active connections
server accepts handled requests Number of accepted, handled connections and total requests
Reading Number of connections where Nginx is reading the request header
Writing Number of connections where Nginx is writing the response
Waiting Number of idle connections (waiting for a request)

Was this article helpful?