Skip to main content

Lesson 3 of 8

Nginx vs Apache - PHP Request Lifecycle

Nginx and Apache both serve PHP applications but handle requests fundamentally differently. Understanding how each web server hands requests to PHP-FPM (or mod_php) is essential when debugging slow requests, configuring rewrites for clean URLs, and optimising for high traffic.

14 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Nginx vs Apache - PHP-FPM Architecture & Config

Nginx vs Apache - PHP-FPM Architecture & Config
# ── How Apache handles PHP requests ─────────────────────────
# Architecture option 1: mod_php (embedded PHP interpreter)
# - PHP runs INSIDE Apache worker processes
# - Every Apache process loads the PHP interpreter (memory-heavy)
# - PHP code executes synchronously
# - Simple config - no separate PHP process manager needed
# - Still used: shared hosting, older setups

# Architecture option 2: Apache + PHP-FPM (recommended)
# - Apache handles HTTP, forwards PHP requests to PHP-FPM via FastCGI
# - PHP-FPM manages a pool of PHP worker processes separately
# - Apache and PHP scale independently
# - More memory-efficient

# .htaccess - Apache rewrite for PHP front-controller pattern
# (file in /var/www/html/public/.htaccess)
# <IfModule mod_rewrite.c>
#     RewriteEngine On
#     RewriteCond %{REQUEST_FILENAME} !-f    # not an existing file
#     RewriteCond %{REQUEST_FILENAME} !-d    # not an existing directory
#     RewriteRule ^ index.php [L]            # send to front controller
# </IfModule>

# ── How Nginx handles PHP requests ────────────────────────────
# Architecture: Nginx ALWAYS uses PHP-FPM (no mod_php equivalent)
# Nginx: event-driven, non-blocking - serves static files extremely fast
# PHP-FPM: process pool for PHP execution - separate, manageable
# Communication: FastCGI protocol (Unix socket or TCP)
#
# Request flow:
# Browser → Nginx (checks: static file? if YES → serve directly)
#                          (PHP file? → forward to PHP-FPM via FastCGI)
#         → PHP-FPM → executes PHP → returns response → Nginx → Browser
#
# Static files served by Nginx at ~10x speed of Apache mod_php

# ── Nginx server block (virtual host) ────────────────────────
# /etc/nginx/sites-available/blog.conf

server {
    listen 80;
    listen [::]:80;
    server_name  blog.example.com www.blog.example.com;
    return 301   https://$server_name$request_uri;  # Force HTTPS
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name  blog.example.com www.blog.example.com;

    root         /var/www/html/blog/public;
    index        index.php;

    # SSL certificates (from Let's Encrypt)
    ssl_certificate     /etc/letsencrypt/live/blog.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/blog.example.com/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;

    # Security headers
    add_header X-Frame-Options         "DENY";
    add_header X-Content-Type-Options  "nosniff";
    add_header Referrer-Policy         "strict-origin-when-cross-origin";
    add_header Permissions-Policy      "camera=(), microphone=()";

    # Static assets - serve directly, cache 1 year
    location ~* .(css|js|jpg|jpeg|png|gif|webp|svg|ico|woff2|woff|ttf)$ {
        expires     1y;
        add_header  Cache-Control "public, immutable";
        access_log  off;
    }

    # PHP front-controller - all non-file routes go to index.php
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # PHP-FPM handler
    location ~ .php$ {
        try_files      $uri =404;
        fastcgi_pass   unix:/run/php/php8.2-fpm.sock;  # Unix socket (faster than TCP)
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include        fastcgi_params;

        # Buffer settings
        fastcgi_buffering        on;
        fastcgi_buffer_size      128k;
        fastcgi_buffers          4 256k;
        fastcgi_connect_timeout  60s;
        fastcgi_send_timeout     60s;
        fastcgi_read_timeout     60s;
    }

    # Block access to hidden files (.env, .git, .htaccess)
    location ~ /. {
        deny all;
        access_log off;
        log_not_found off;
    }

    client_max_body_size 20M;   # Max upload size (match PHP post_max_size)
    gzip             on;
    gzip_comp_level  5;
    gzip_types       text/plain text/css application/json application/javascript;
}

# ── PHP-FPM pool configuration ─────────────────────────────────
# /etc/php/8.2/fpm/pool.d/www.conf
# pm = dynamic
# pm.max_children      = 20          ; Max simultaneous PHP workers
# pm.start_servers     = 4           ; Workers at start
# pm.min_spare_servers = 2           ; Keep at least N idle workers
# pm.max_spare_servers = 8           ; Kill workers above N idle
# pm.max_requests      = 500         ; Restart worker after N requests (prevent memory leaks)

Quick Quiz

Tip

Tip

Practice Nginx vs Apache PHP Request Lifecycle in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Nginx vs Apache - PHP Request Lifecycle

Practice Task

Note

Practice Task - (1) Write a working example of Nginx vs Apache PHP Request Lifecycle from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Nginx vs Apache PHP Request Lifecycle is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done