MASTER
HIGH PERFORMANCE

// The web server built for speed.

NGINX IS THE CHOICE FOR PERFORMANCE.

Originally created to solve the C10K problem (handling 10,000+ concurrent connections), NGINX powers over 400 million websites worldwide. It's the secret behind Netflix, Instagram, and WordPress.com.

WHY NGINX?

NGINX uses an asynchronous, event-driven architecture that handles massive traffic with minimal memory. It's faster than Apache for static content and excels as a reverse proxy and load balancer.

TAKE CONTROL OF PERFORMANCE.

Learn to configure NGINX as a web server, reverse proxy, or load balancer. Master caching, SSL/TLS, and optimization techniques to build lightning-fast deployments.

BEGIN YOUR JOURNEY →

// The Path to Mastery

12 lessons. Complete NGINX control.

LESSON 01

Introduction to NGINX

High-performance web server and reverse proxy

Beginner
LESSON 02

Installing NGINX

Set up on Debian/Ubuntu and RHEL/CentOS

Beginner
LESSON 03

Configuration Files & Directives

Master nginx.conf structure

Beginner
LESSON 04

Server Blocks (Virtual Hosts)

Host multiple websites on one server

Intermediate
LESSON 05

SSL/TLS & HTTPS

Secure sites with Let's Encrypt certificates

Intermediate
LESSON 06

Reverse Proxy

Forward requests to backend applications

Intermediate
LESSON 07

Load Balancing

Distribute traffic across multiple servers

Intermediate
LESSON 08

Caching

Improve performance with content caching

Intermediate
LESSON 09

Security Best Practices

Harden NGINX against attacks

Advanced
LESSON 10

Performance Optimization

Tune worker processes and buffers

Advanced
LESSON 11

PHP with NGINX

Configure PHP-FPM for dynamic content

Intermediate
LESSON 12

Common Pitfalls & Debugging

Fix configuration errors and optimize

Advanced

// Why NGINX

NGINX (pronounced "engine-x") was created by Igor Sysoev in 2004 to solve the C10K problem. Its event-driven, asynchronous architecture makes it incredibly efficient at handling concurrent connections.

Unlike Apache's process-per-request model, NGINX uses a single worker process that can handle thousands of connections simultaneously. This makes it ideal for high-traffic sites and real-time applications.

NGINX is dual-licensed: free open-source version and commercial NGINX Plus with additional features. The open-source version is perfect for most use cases.

When performance matters, the web runs on NGINX. Now you can too.

// Tools & References

📖 Official Docs

NGINX Documentation

nginx.org/en/docs

🔧 NGINX Basics

Beginner's Guide

nginx.org/beginners

🔐 SSL Certificates

Let's Encrypt - Free SSL/TLS

letsencrypt.org

🖥️ Module Reference

All NGINX modules

nginx.org/modules

⚡ Performance

Optimization Guide

nginx.com/performance

🔒 Security

NGINX Security Best Practices

nginx.com/security

// Introduction to NGINX

×

What is NGINX?

NGINX (engine-x) is a high-performance web server, reverse proxy, and load balancer. Created in 2004 by Igor Sysoev, it was designed to solve the C10K problem—handling 10,000+ concurrent connections.

Why NGINX?

NGINX offers several advantages:

  • Event-driven: Handles thousands of connections per process
  • Low memory: Uses minimal RAM compared to Apache
  • Fast: Serves static content much faster than Apache
  • Versatile: Acts as web server, proxy, or load balancer
  • Battle-tested: Powers Netflix, Instagram, WordPress.com
MARKET SHARE: NGINX serves approximately 35% of all websites worldwide, making it the most popular web server after Apache.

NGINX vs Apache

Architecture Event-driven, async Process/thread per request
Static Content Faster Slower
Dynamic Content Via external handlers Native modules
Configuration .conf files .htaccess + conf
OS Support All Unix-like All

Checking NGINX Version

$ nginx -v nginx version: nginx/1.24.0 (Ubuntu)
$ nginx -V nginx version: nginx/1.24.0 built by gcc 11.4.0 built with OpenSSL 3.0.2 TLS SNI support enabled ...

NGINX File Structure (Ubuntu/Debian)

  • /etc/nginx/ - Main configuration directory
  • /etc/nginx/nginx.conf - Main config file
  • /etc/nginx/sites-available/ - Site configurations
  • /etc/nginx/sites-enabled/ - Enabled sites (symlinks)
  • /etc/nginx/snippets/ - Reusable config snippets
  • /var/log/nginx/ - Log files
  • /var/www/html/ - Default document root

Quiz

1. NGINX was created to solve the _____ problem.

Hint: 10,000 connections

2. NGINX uses an _____ architecture.

Hint: Async

3. NGINX serves _____ content faster than Apache.

Hint: HTML, images, etc.

4. The default document root is _____.

Hint: Under /var/www

5. NGINX is pronounced _____.

Hint: Not

6. The main config file is _____.

Hint: In /etc/nginx/

7. To check NGINX version, use _____ -v.

Hint: The binary name

8. Sites are configured in _____ directory.

Hint: Available sites

Show Answers

Answers

  1. C10K
  2. event-driven
  3. static
  4. /var/www/html
  5. engine-x
  6. nginx.conf
  7. nginx
  8. /etc/nginx/sites-available

// Installing NGINX

×

Installation on Ubuntu/Debian

Installing NGINX on Debian-based systems is straightforward using apt:

$ sudo apt update Hit:1 http://archive.ubuntu.com/ubuntu jammy InRelease Reading package lists... Done
$ sudo apt install nginx Reading package lists... Done The following NEW packages will be installed: nginx nginx-common nginx-core Do you want to continue? [Y/n] y

Installation on CentOS/RHEL/Fedora

On RHEL-based systems, add the EPEL repository first:

$ sudo dnf install epel-release Last metadata expiration check: 0:00:01 ago Package epel-release-9-4.noarch is already installed.
$ sudo dnf install nginx Last metadata expiration check: 0:00:01 ago Package nginx-1.24.0-1.el9.x86_64 is already installed.

Starting and Enabling NGINX

$ sudo systemctl start nginx # Start NGINX
$ sudo systemctl enable nginx # Enable on boot
$ sudo systemctl restart nginx # Restart (after config changes)

Testing Your Installation

After installation, verify NGINX is serving pages:

$ curl localhost Welcome to nginx! ...

Or open http://localhost in your browser. You should see the default NGINX welcome page.

Essential NGINX Packages

  • nginx - Main server package
  • nginx-common - Common files
  • nginx-core - Core binaries

Testing Configuration

$ sudo nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
IMPORTANT: Always test your NGINX configuration before reloading. Use 'nginx -t' to check for syntax errors.

Quiz

1. On Ubuntu, NGINX is installed with the _____ command.

Hint: Uses apt package manager

2. On CentOS, you need _____ first.

Hint: Extra Packages

3. To start NGINX on systemd, use _____.

Hint: systemctl

4. To enable NGINX on boot, use _____ enable.

Hint: systemctl enable

5. To test config syntax, use _____.

Hint: Test configuration

6. After config changes, you should _____ NGINX.

Hint: systemctl reload

7. You can test NGINX with _____ localhost.

Hint: Command-line HTTP client

8. The configuration test shows _____.

Hint: Configuration is valid

Show Answers

Answers

  1. apt install nginx
  2. epel-release
  3. systemctl start nginx
  4. systemctl
  5. nginx -t
  6. reload
  7. curl
  8. syntax is ok

// Configuration Files & Directives

×

Understanding NGINX Configuration

NGINX uses a hierarchical configuration system with directives organized in blocks. Understanding this structure is key to effective server administration.

Main Configuration File

The primary configuration file is /etc/nginx/nginx.conf:

user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; server { listen 80; server_name example.com; root /var/www/html; } }

Key Directives

user

Specifies which user NGINX runs as:

user www-data;

worker_processes

Number of worker processes (auto = number of CPU cores):

worker_processes auto;

worker_connections

Maximum connections per worker:

worker_connections 1024;

listen

IP and port to listen on:

listen 80; listen 443 ssl http2;

server_name

Domain name(s) for the server block:

server_name example.com www.example.com;

root

Document root directory:

root /var/www/html;

Location Blocks

The location block matches URI patterns:

location / { root /var/www/html; } location /images/ { root /data; } location ~ \\.php$ { fastcgi_pass unix:/run/php/php-fpm.sock; }

Include Files

NGINX uses include directives to modularize configuration:

include /etc/nginx/mime.types; include /etc/nginx/sites-enabled/*; include /etc/nginx/conf.d/*.conf;

Quiz

1. The main NGINX configuration file is _____.

Hint: In /etc/nginx/

2. The _____ directive specifies the web root directory.

Hint: Where files are served from

3. worker_processes _____ uses all CPU cores.

Hint: Automatic detection

4. The maximum connections per worker is _____.

Hint: In events block

5. The location block matches _____.

Hint: URL paths

6. The _____ directive specifies domain names.

Hint: Domain names

7. To include other config files, use _____.

Hint: Include directive

8. NGINX runs as _____ by default on Ubuntu.

Hint: Unprivileged user

Show Answers

Answers

  1. nginx.conf
  2. root
  3. auto
  4. worker_connections
  5. URI patterns
  6. server_name
  7. include
  8. www-data

// Server Blocks (Virtual Hosts)

×

What are Server Blocks?

Server blocks in NGINX (equivalent to Apache's Virtual Hosts) allow you to serve multiple websites from a single server. Each block defines configuration for a specific domain.

Creating a Server Block

Create a configuration file in /etc/nginx/sites-available/:

server { listen 80; listen [::]:80; server_name example.com www.example.com; root /var/www/example.com; index index.html index.htm; location / { try_files $uri $uri/ =404; } error_log /var/log/nginx/example.com-error.log; access_log /var/log/nginx/example.com-access.log; }

Enabling Sites

$ sudo ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/ # Enable site (create symlink)
$ sudo rm /etc/nginx/sites-enabled/example.com.conf # Disable site (remove symlink)

Default Server Block

The default site serves requests that don't match any server_name:

$ ls /etc/nginx/sites-enabled/ default example.com.conf

Multiple Sites on Same Server

You can have multiple server blocks:

$ ls /etc/nginx/sites-available/ default example.com.conf blog.example.com.conf api.example.com.conf

Catch-all Server Block

Handle all requests to unknown domains:

server { listen 80 default_server; server_name _; root /var/www/default; }

Reload NGINX

$ sudo nginx -t && sudo systemctl reload nginx # Test and reload configuration
NOTE: Unlike Apache, NGINX does not have a command to enable/disable sites. You must create/remove symlinks manually.

Quiz

1. NGINX server blocks are equivalent to Apache

Hint: Multiple sites

2. To enable a site, create a _____ to sites-enabled.

Hint: Symbolic link

3. The server_name directive defines _____ names.

Hint: Domain names

4. Server block configs are in _____ directory.

Hint: Available sites

5. The default_server option makes a site _____.

Hint: Default for unmatched

6. server_name _____ matches any domain.

Hint: Underscore

7. Always test config with _____ before reload.

Hint: Test configuration

8. The default site serves requests matching no _____.

Hint: Domain name

Show Answers

Answers

  1. virtual hosts
  2. symlink
  3. domain
  4. /etc/nginx/sites-available
  5. catch-all
  6. _
  7. nginx -t
  8. server_name

// SSL/TLS & HTTPS

×

Why SSL/TLS?

SSL/TLS encrypts communication between the server and clients, protecting sensitive data from interception. It's essential for security, SEO, and user trust.

SSL Certificate Types

  • DV (Domain Validation): Basic, verifies domain ownership
  • OV (Organization Validation): Verifies organization identity
  • EV (Extended Validation): Highest trust, green bar
  • Self-signed: For testing only, not trusted by browsers

Creating Self-Signed Certificate (Testing)

$ sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/nginx-selfsigned.key -out /etc/ssl/certs/nginx-selfsigned.crt Generating a 2048 bit RSA private key .......................+++ ....+++ writing new private key to '/etc/ssl/private/nginx-selfsigned.key'

Creating SSL Server Block

server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name example.com; root /var/www/html; ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt; ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; }

SSL Configuration Best Practices

ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256; ssl_prefer_server_ciphers on; ssl_session_cache shared:SSL:10m; ssl_session_timeout 1d;

Forcing HTTPS

Redirect all HTTP traffic to HTTPS:

server { listen 80; listen [::]:80; server_name example.com; return 301 https://$host$request_uri; }

Using Let's Encrypt (Production)

$ sudo apt install certbot python3-certbot-nginx
$ sudo certbot --nginx -d example.com -d www.example.com Saving debug log to /var/log/letsencrypt/letsencrypt.log Successfully received certificate. Certificate is saved at: /etc/letsencrypt/live/example.com/fullchain.pem Key is saved at: /etc/letsencrypt/live/example.com/privkey.pem

Auto-renewal

$ sudo certbot renew --dry-run # Test auto-renewal

Quiz

1. _____ encrypts communication between server and client.

Hint: HTTPS

2. Let

Hint: DV certificates

3. The ssl_certificate directive specifies the _____.

Hint: Public key file

4. The ssl_certificate_key directive specifies the _____.

Hint: Secret key file

5. To redirect HTTP to HTTPS, use _____ directive.

Hint: 301 redirect

6. Self-signed certificates are for _____ only.

Hint: Not production

7. certbot is used to obtain _____ certificates.

Hint: From Let

8. HTTP/2 requires _____.

Hint: Must be HTTPS

Show Answers

Answers

  1. SSL/TLS
  2. free
  3. certificate
  4. private key
  5. return
  6. testing
  7. SSL/TLS
  8. SSL/TLS

// Reverse Proxy

×

What is a Reverse Proxy?

A reverse proxy sits between clients and backend servers. It forwards client requests to appropriate backends and returns responses. NGINX excels at this role.

Why Use a Reverse Proxy?

  • Load balancing: Distribute traffic across multiple servers
  • Security: Hide backend servers from direct internet access
  • SSL termination: Handle HTTPS at the proxy
  • Caching: Store responses for faster delivery
  • Compression: Reduce bandwidth

Basic Reverse Proxy Configuration

server { listen 80; server_name example.com; location / { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }

Proxy Headers

Important headers for backend servers:

proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host;

Proxy to Unix Socket

For PHP-FPM and other services:

location ~ \\.php$ { proxy_pass http://unix:/run/php/php-fpm.sock; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; }

WebSocket Proxying

location /ws/ { proxy_pass http://localhost:8080; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; }

Proxy Timeout Settings

proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s;

Quiz

1. A reverse _____ sits between clients and backend servers.

Hint: Forwards requests

2. The proxy_pass directive specifies the _____ server.

Hint: Target server

3. X-Real-IP header contains the _____ IP address.

Hint: Original client

4. For WebSocket, set Connection to _____.

Hint: Upgrade header

5. proxy_pass can use a _____ socket.

Hint: PHP-FPM

6. X-Forwarded-For contains the _____ IP.

Hint: Client IP through proxies

7. To hide backend servers, use a _____ proxy.

Hint: Reverse proxy

8. The Host header should be set to _____.

Hint: Variable

Show Answers

Answers

  1. proxy
  2. backend
  3. client
  4. upgrade
  5. unix
  6. original
  7. reverse
  8. $host

// Load Balancing

×

What is Load Balancing?

Load balancing distributes incoming traffic across multiple backend servers. NGINX can balance load using various algorithms and health checks.

Load Balancing Methods

  • round_robin: Default, each request in order
  • least_conn: Fewest active connections
  • ip_hash: Same client to same server
  • weighted: Manual distribution
  • least_time: Fastest response (NGINX Plus)

Basic Load Balancer Configuration

upstream backend { server backend1.example.com:8080; server backend2.example.com:8080; server backend3.example.com:8080; } server { listen 80; server_name example.com; location / { proxy_pass http://backend; } }

Weighted Load Balancing

upstream backend { server backend1.example.com:8080 weight=5; server backend2.example.com:8080 weight=3; server backend3.example.com:8080 weight=2; }

Least Connections

upstream backend { least_conn; server backend1.example.com:8080; server backend2.example.com:8080; }

IP Hash

Sticky sessions - same client goes to same server:

upstream backend { ip_hash; server backend1.example.com:8080; server backend2.example.com:8080; }

Health Checks

Mark servers as down if they fail:

upstream backend { server backend1.example.com:8080 max_fails=3 fail_timeout=30s; server backend2.example.com:8080 max_fails=3 fail_timeout=30s; server backend3.example.com:8080 backup; }

Backup Servers

upstream backend { server backend1.example.com:8080; server backend2.example.com:8080; server backend3.example.com:8080 backup; }

Quiz

1. Load _____ distributes traffic across servers.

Hint: Distribution

2. _____ method sends requests in order.

Hint: Default method

3. _____ method uses fewest active connections.

Hint: Load balancing

4. ip_hash provides _____ sessions.

Hint: Same client to same server

5. The backup flag marks a server as _____.

Hint: Fallback

6. max_fails determines server _____ threshold.

Hint: Failure count

7. Upstream blocks define _____ servers.

Hint: Target servers

8. Weight=5 gives a server _____ times more requests.

Hint: Five times

Show Answers

Answers

  1. balancing
  2. round_robin
  3. least_conn
  4. sticky
  5. backup
  6. failure
  7. backend
  8. 5

// Caching

×

NGINX Caching

NGINX can cache responses from backend servers, reducing load and improving response times dramatically.

Enabling Proxy Cache

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=100m inactive=60m use_temp_path=off; server { listen 80; server_name example.com; location / { proxy_pass http://backend; proxy_cache my_cache; proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m; proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504; } }

Cache Parameters

  • levels: Directory structure
  • keys_zone: Shared memory for cache keys
  • max_size: Maximum cache size
  • inactive: Time before unused items are purged
  • use_temp_path: Use 0 to write directly to cache

Bypassing Cache

location /api/ { proxy_pass http://backend; proxy_cache_bypass $http_cache_control; proxy_no_cache $http_cache_control; }

Cache Purging

Install ngx_cache_purge module for on-demand purging:

location ~ /purge(/.*) { proxy_pass http://backend$1; proxy_cache_purge my_cache $1; }

FastCGI Cache (for PHP)

fastcgi_cache_path /var/cache/nginx/fcgi levels=1:2 keys_zone=fcgi_cache:10m max_size=100m inactive=60m; location ~ \\.php$ { fastcgi_pass unix:/run/php/php-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_cache fcgi_cache; fastcgi_cache_valid 200 60m; add_header X-FastCGI-Cache $upstream_cache_status; }

Browser Caching

Set headers for client-side caching:

location ~* \\.(jpg|jpeg|png|gif|ico|css|js)$ { expires 30d; add_header Cache-Control "public, no-transform"; }

Quiz

1. Proxy cache stores responses from _____ servers.

Hint: Proxy target

2. The keys_zone directive defines _____ memory.

Hint: In memory

3. proxy_cache_bypass skips cache based on _____.

Hint: HTTP headers

4. FastCGI cache is for _____ content.

Hint: PHP, etc.

5. The expires directive sets _____ caching.

Hint: Client-side

6. X-FastCGI-Cache shows cache _____.

Hint: HIT, MISS, etc.

7. Cache size is limited by _____ parameter.

Hint: Maximum size

8. Inactive items are purged after _____ time.

Hint: inactive parameter

Show Answers

Answers

  1. backend
  2. shared
  3. headers
  4. dynamic
  5. browser
  6. status
  7. max_size
  8. inactive

// Security Best Practices

×

NGINX Security

Securing NGINX is critical. A misconfigured web server can expose sensitive data or become a vector for attacks.

Hide NGINX Version

Don't reveal server version to attackers:

server_tokens off;

Disable Directory Listing

location / { autoindex off; }

Protect Sensitive Files

Block access to config files:

location ~ /\\. { deny all; } location ~ /\\.(conf|log|env)$ { deny all; }

Limit Request Size

Prevent DoS attacks with large requests:

client_max_body_size 8k; client_body_timeout 10s; client_header_timeout 10s;

Rate Limiting

Limit requests from a single IP:

limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s; server { location / { limit_req zone=mylimit burst=20 nodelay; } }

Security Headers

Add headers to protect against common attacks:

add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always; add_header Content-Security-Policy "default-src 'self'" always;

Allow Specific IP Addresses

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

Run as Unprivileged User

NGINX should run as www-data, not root (already configured by default):

user www-data; worker_processes auto;

File Permissions

$ chmod -R 755 /var/www/html # Directories
$ chmod -R 644 /var/www/html/*.html # Files

Quiz

1. server_tokens _____ hides NGINX version.

Hint: Hide version

2. autoindex _____ disables directory listing.

Hint: Disable

3. Security headers are added with _____ header.

Hint: Header directive

4. X-Frame-Options prevents _____ attacks.

Hint: iframe embedding

5. client_max_body_size prevents _____ attacks.

Hint: Denial of Service

6. NGINX should run as _____, not root.

Hint: Unprivileged user

7. rate limiting uses _____ zone.

Hint: Rate limit

8. deny all blocks _____ addresses.

Hint: IP addresses

Show Answers

Answers

  1. off
  2. off
  3. add_header
  4. clickjacking
  5. DoS
  6. www-data
  7. limit_req_zone
  8. IP

// Performance Optimization

×

NGINX Performance Tuning

Optimizing NGINX improves page load times, reduces server load, and provides better user experience.

Worker Process Configuration

worker_processes auto; worker_rlimit_nofile 65535; worker_connections 2048;

Event Processing

Use epoll for Linux:

events { worker_connections 2048; use epoll; multi_accept on; }

Enable Gzip Compression

gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_types text/plain text/css text/xml application/json application/javascript application/rss+xml image/svg+xml; gzip_min_length 256;

Keep-Alive Connections

Reduce overhead with persistent connections:

upstream backend { server backend1.example.com:8080; keepalive 32; } location / { proxy_http_version 1.1; proxy_set_header Connection ""; proxy_pass http://backend; }

Buffering

Optimize proxy buffering:

proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 16k; proxy_busy_buffers_size 24k;

Open File Caching

Cache file metadata:

open_file_cache max=10000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on;

Sendfile

Use kernel sendfile for faster file serving:

sendfile on; tcp_nopush on; tcp_nodelay on;

Reset Timed Out Connections

reset_timedout_connection on;

Quiz

1. worker_processes _____ auto-detects CPU cores.

Hint: Automatic

2. Use _____ for event processing on Linux.

Hint: Linux event model

3. Gzip _____ determines compression level.

Hint: 1-9

4. Keep-alive reduces _____ overhead.

Hint: TCP overhead

5. _____ caching stores file metadata.

Hint: File cache

6. Sendfile uses _____ for file transfer.

Hint: OS kernel

7. tcp_nopush optimizes _____ packets.

Hint: Network packets

8. proxy_buffers should be sized based on _____ content.

Hint: Response size

Show Answers

Answers

  1. auto
  2. epoll
  3. comp_level
  4. connection
  5. open_file_cache
  6. kernel
  7. TCP
  8. backend

// PHP with NGINX

×

NGINX with PHP-FPM

NGINX doesn't have native PHP support like Apache. Instead, it passes PHP requests to PHP-FPM (FastCGI Process Manager).

Installing PHP-FPM

$ sudo apt install php-fpm php-mysql The following NEW packages will be installed: php-fpm php8.1-fpm php8.1-mysql ...

Check PHP-FPM Socket

$ ls -la /run/php/ php8.1-fpm.sock

Basic PHP Configuration

server { listen 80; server_name example.com; root /var/www/html; index index.php index.html; location / { try_files $uri $uri/ =404; } location ~ \\.php$ { include /etc/nginx/snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php8.1-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include /etc/nginx/fastcgi_params; } location ~ /\\.ht { deny all; } }

Using Snippets (Ubuntu)

Ubuntu includes a fastcgi-php.conf snippet:

$ cat /etc/nginx/snippets/fastcgi-php.conf location ~ \\.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\\.php)(/.+)$; include fastcgi_params; fastcgi_index Index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; }

PHP-FPM Pool Configuration

Edit /etc/php/8.1/fpm/pool.d/www.conf:

[www] user www-data group www-data listen /run/php/php8.1-fpm.sock listen.owner www-data listen.group www-data pm dynamic pm.max_children 50 pm.start_servers 5 pm.min_spare_servers 5 pm.max_spare_servers 35

PHP Configuration (php.ini)

max_execution_time 30 memory_limit 128M upload_max_filesize 20M post_max_size 25M

Testing PHP

$ echo '' | sudo tee /var/www/html/info.php

Quiz

1. NGINX passes PHP to _____.

Hint: FastCGI Process Manager

2. The fastcgi_pass directive specifies the _____.

Hint: Unix socket

3. PHP-FPM uses the _____ protocol.

Hint: Interface

4. SCRIPT_FILENAME contains the _____ path.

Hint: PHP file path

5. Ubuntu has a _____ for PHP config.

Hint: fastcgi-php.conf

6. PM in PHP-FPM stands for _____ Manager.

Hint: Process Manager

7. To test PHP, create a _____ file.

Hint: phpinfo()

8. PHP-FPM pools are configured in _____ directory.

Hint: Pool configs

Show Answers

Answers

  1. PHP-FPM
  2. socket
  3. FastCGI
  4. file
  5. snippet
  6. Process
  7. info.php
  8. /etc/php/*/fpm/pool.d

// Common Pitfalls & Debugging

×

NGINX Troubleshooting

Understanding common issues and how to debug them is essential for NGINX administration.

Common Issues

  • 403 Forbidden: Usually file/directory permissions or wrong path
  • 404 Not Found: Wrong root path or try_files misconfiguration
  • 502 Bad Gateway: Backend service down or socket permission issues
  • 504 Gateway Timeout: Backend too slow or timeout too short
  • 111 Connection Refused: Backend not listening on expected port

Testing Configuration

$ sudo nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful

View Error Logs

$ sudo tail -f /var/log/nginx/error.log # Watch errors in real-time

View Access Logs

$ sudo tail -f /var/log/nginx/access.log # Watch requests in real-time

Debug Mode

Enable debug logging:

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

Check Port Conflicts

$ sudo netstat -tlnp | grep :80 tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 1234/nginx: master

Check File Permissions

$ ls -la /var/www/html/ # Check ownership and permissions

Check Socket Permissions

$ ls -la /run/php/ # Check PHP-FPM socket

Verify Backend is Running

$ curl -v http://localhost:3000 # Test backend directly

Reload vs Restart

$ sudo systemctl reload nginx # Graceful reload (serves existing requests)
$ sudo systemctl restart nginx # Full restart (interrupts active connections)

Verify Syntax with -T

$ sudo nginx -T | head -50 # View entire config

Common Fixes

403 Forbidden

$ sudo chmod -R 755 /var/www # Fix directory permissions

502 with PHP-FPM

$ sudo chown -R www-data:www-data /var/www # Fix ownership

Quiz

1. 403 Forbidden is usually _____ issues.

Hint: File/directory

2. 502 Bad Gateway usually means _____ is down.

Hint: Backend service

3. To test config, use _____ -t.

Hint: Test command

4. Debug logging uses _____ level.

Hint: Most verbose

5. reload is _____ (interrupts/no interrupts).

Hint: No interrupts

6. netstat shows _____ usage.

Hint: Network ports

7. PHP-FPM 502 is often socket _____ issues.

Hint: Ownership

8. nginx _____ shows full config.

Hint: Test and view

Show Answers

Answers

  1. permission
  2. backend
  3. nginx
  4. debug
  5. graceful
  6. port
  7. permission
  8. -T