Nginx Configuration Guide: Best Practices

author

By Freecoderteam

Oct 14, 2025

4

image

Nginx Configuration Guide: Best Practices

Nginx is one of the most popular web servers and reverse proxies in the world. Its high performance, low memory footprint, and rich feature set make it a go-to choice for hosting websites, APIs, and applications. However, configuring Nginx can be complex, especially for those new to it. This guide will walk you through best practices for configuring Nginx, including security, performance optimization, and practical insights.

Table of Contents

Understanding Nginx Configuration Files

Nginx's configuration is primarily managed through its configuration files, typically located in /etc/nginx/nginx.conf (the main configuration file) and /etc/nginx/sites-available/ (where server-specific configurations reside). Understanding the structure of these files is crucial for effective configuration.

Key Sections in Nginx Configuration

  1. http Block: Contains global configuration settings that apply to all virtual hosts.
  2. server Block: Defines individual virtual hosts or sites.
  3. location Block: Specifies how to handle different parts of a site (e.g., static files, dynamic content).

Example Configuration Structure

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

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

    # Virtual host configuration
    server {
        listen 80;
        server_name example.com www.example.com;

        root /var/www/example;
        index index.html index.php;

        location / {
            try_files $uri $uri/ =404;
        }

        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php8.1-fpm.sock;
        }
    }
}

Best Practices for Security

Securing your Nginx server is critical to protect against potential threats. Here are some best practices:

1. Use HTTPS

Always serve your content over HTTPS to encrypt data in transit. Use tools like Let's Encrypt to obtain free SSL/TLS certificates.

Example: Enabling HTTPS

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /etc/ssl/certs/ssl-cert.crt;
    ssl_certificate_key /etc/ssl/private/ssl-cert.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
}

server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri; # Redirect HTTP to HTTPS
}

2. Disable Directory Browsing

Prevent users from browsing directory contents by setting autoindex to off.

server {
    location / {
        autoindex off;
    }
}

3. Limit Request Size

Prevent large file uploads or requests that could overwhelm your server.

http {
    client_max_body_size 5M; # Limit request size to 5MB
}

4. Use X-Content-Type-Options and Content-Security-Policy

These headers help mitigate security vulnerabilities like MIME-type sniffing and XSS attacks.

server {
    add_header X-Content-Type-Options nosniff;
    add_header Content-Security-Policy "default-src 'self'";
}

5. Rate Limiting

Prevent abuse by limiting the number of requests from a single IP address over a given time.

http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

    server {
        location /api {
            limit_req zone=one burst=5 nodelay;
        }
    }
}

Performance Optimization

Optimizing Nginx for performance ensures faster response times and better resource utilization.

1. Enable Gzip Compression

Compress responses to reduce data transfer size, especially for text-based content like HTML, CSS, and JavaScript.

http {
    gzip on;
    gzip_proxied any;
    gzip_types text/plain text/css application/javascript application/json;
    gzip_vary on;
}

2. Use Caching

Nginx can act as a reverse proxy or load balancer and cache content to reduce the load on upstream servers.

http {
    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1G inactive=60m;
    proxy_cache my_cache;

    server {
        location / {
            proxy_pass http://backend;
            proxy_cache_revalidate on;
            proxy_cache_valid 200 302 10m;
            proxy_cache_valid 404 1m;
        }
    }
}

3. Optimize TCP Keep-Alive

Properly configure keep-alive to reduce the number of TCP connections, improving performance.

http {
    keepalive_timeout 75s;
    keepalive_requests 100;
}

4. Use FastCGI Caching

If you're using PHP-FPM, Nginx can cache PHP outputs to serve static content without re-executing scripts.

http {
    fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=my_fastcgi_cache:10m max_size=1G inactive=60m;

    server {
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php8.1-fpm.sock;
            fastcgi_cache my_fastcgi_cache;
            fastcgi_cache_valid 200 301 302 1h;
            fastcgi_cache_bypass $http_cookie;
            fastcgi_no_cache $http_cookie;
        }
    }
}

Efficient Use of Server Blocks

Organizing your server blocks properly ensures better maintainability and scalability.

1. Use Include Directives

Break down your configuration into multiple files for better organization. For example:

http {
    include /etc/nginx/sites-enabled/*;
}

2. Server Name Hashing

Enable server name hashing to improve performance when dealing with many virtual hosts.

http {
    server_names_hash_bucket_size 128;
}

3. Avoid Wildcard Server Blocks

Wildcard server blocks can cause security risks. Always explicitly specify server_name.

server {
    listen 80;
    server_name _; # Wildcard, not recommended
    return 444;    # Close the connection
}

Error Handling and Logging

Proper error handling and logging are essential for troubleshooting and monitoring.

1. Custom Error Pages

Create custom error pages to provide better user experiences and maintain brand consistency.

server {
    error_page 404 /custom_404.html;
    location = /custom_404.html {
        internal;
    }
}

2. Configure Access and Error Logs

Log requests and errors to monitor server behavior and identify issues.

http {
    access_log /var/log/nginx/access.log combined;
    error_log /var/log/nginx/error.log warn;
}

3. Rotate Logs

Set up log rotation to prevent log files from growing too large.

# Example logrotate configuration
/var/log/nginx/*.log {
    daily
    missingok
    rotate 7
    compress
    delaycompress
    notifempty
    create 0640 root adm
    sharedscripts
    postrotate
        /etc/init.d/nginx reload > /dev/null 2>&1 || true
    endscript
}

Conclusion

Configuring Nginx effectively requires a balance of security, performance, and maintainability. By following the best practices outlined in this guide, you can ensure your Nginx server is robust, secure, and optimized for high performance. Remember to test changes in a staging environment before deploying them to production and regularly review and update your configurations to adapt to new requirements and security threats.

Additional Resources

By implementing these best practices, you'll be well on your way to managing a high-performing and secure Nginx server. Happy configuring!

Share this post :

Subscribe to Receive Future Updates

Stay informed about our latest updates, services, and special offers. Subscribe now to receive valuable insights and news directly to your inbox.

No spam guaranteed, So please don’t send any spam mail.