December 30, 2024
· 6 min readCGI, FastCGI, php-fpm, and nginx: The Web Server Squad You Need to Know
Ever wondered how your shiny new blogâlike my recently deployed CodeBit Chroniclesâflies from server to screen? Itâs all thanks to nginx, CGI, FastCGI, and php-fpm working together. These tools handle everything from static assets to dynamic PHP APIs powering a Next.js frontend. In this guide, weâll break down their roles with examples from my blog deployment, showing how they bring it all to life. New to servers or a seasoned dev? Letâs dive into the fun!
So, I just launched "CodeBit Chronicles," my new blog about coding adventures, built with Next.js. Itâs got snappy static pages, server-rendered posts, and a PHP API for some backend magic. How does it all get to your browser so fast? Itâs not pixie dustâitâs nginx, CGI, FastCGI, and php-fpm pulling the strings. Knowing these tools has been a game-changer for my deployment, and Iâm excited to share the basics with you, using my blog as our playground. Letâs jump in with some CodeBit-inspired examples!
Kicking Off with nginx: Serving Static Goodies
Letâs start with nginx, the speedy web server, handling static files for CodeBit Chronicles. After running next build && next export for static pages, Iâve got:
index.html(the blogâs homepage)styles.css(some sharp styling)codebit.png(my blogâs logo)
These sit in /srv/web/static/codebit. Hereâs a simple nginx config to serve them:
events {}
http {
access_log /var/log/nginx/site_access.log;
error_log /var/log/nginx/site_errors.log;
include mime.types;
server {
listen 80;
server_name 192.168.50.10;
root /srv/web/static/codebit;
}
}Heads Up: This is a starter setupânot production-readyâbut great for learning. Letâs break it down.
nginx Basics: Contexts and Directives
Think of nginx configs like a blog draft with two parts:
-
Contexts: These are like sectionsâscopes where the action happens:
http: The whole draft for all sites.server: One page for CodeBit Chronicles (here,http://192.168.50.10).location: A paragraph for specific URLs (up next!).events: A notes section weâll skip.
Itâs layered:
httpoversees all,serverfocuses on my blog, andlocation(later) zooms into posts. -
Directives: These are the linesâlike
listen 80;âtelling nginx what to do in each section.
Line-by-Line Peek
-
access_log /var/log/nginx/site_access.log;
Every visitor logs here, like:
198.51.100.10 - - [03/Dec/2024] "GET /" 200
Itâs CodeBitâs guestbook. -
error_log /var/log/nginx/site_errors.log;
nginx vents here if it stumbles (e.g., config typos)ânot for 404s, just server quirks. -
include mime.types;
This pulls in a file (like PHPâsinclude()) with file types:text/html html; text/css css; image/png png;Skip it, and
styles.cssmight load as gibberishânginx includes this by default. -
listen 80;
âOpen the blog on port 80!â (HTTP, no SSL yet.) -
server_name 192.168.50.10;
My blogâs address. Iâd prefercodebitchronicles.com, but an IPâs fine for now. -
root /srv/web/static/codebit;
The blogâs base. Requestcodebit.png? nginx grabs/srv/web/static/codebit/codebit.png.
How It Works
Hit http://192.168.50.10, and nginx serves index.htmlâCodeBitâs homepageâby default. The browser then fetches styles.css (http://192.168.50.10/styles.css), and nginx delivers. Static bliss! But Next.js also uses server-side rendering and APIs (say, a PHP backend for post data). nginx doesnât handle that aloneâletâs bring in the PHP crew.
The PHP Crew: CGI, FastCGI, and php-fpm
For CodeBit Chronicles, static files are just the start. Iâve got a PHP API at /api/posts.php feeding dynamic post data to Next.js. nginx doesnât speak PHP, so we need CGI, FastCGI, and php-fpm to bridge the gap.
CGI: The Classic Courier
Whatâs CGI? Common Gateway Interfaceâa protocol, not a tool. Itâs like a delivery service linking web servers to scripts, built for dynamic content (PHP, Python, you name it!). The spec calls it âa simple interface for running external programsâ anywhere.
[[NEWSLETTER]]
How It Works: Each requestâlike http://192.168.50.10/api/posts.phpâspawns a new process to run the PHP. Picture a courier biking one package at a time:
- 1 reader = 1 process.
- 300 readers = 300 processes.
Pros: Simple as pie.
Cons: Resource-heavy! Starting and stopping processes taxes the CPU, and task-switching lags under load. Itâs like sending a new courier per blog readerânot sustainable.
FastCGI: The Fleet Upgrade
Whatâs FastCGI? A protocol boosting CGI. It swaps the âone-process-per-requestâ grind for reusable processesâlike a courier fleet handling multiple deliveries.
How It Works: A team of processes sticks around, serving requests, cutting the cost of constant setup/teardown. Itâs like a blog dispatch crew ready to roll. It can use Unix sockets or TCP (weâll play with both later).
Why Itâs Better: Less CPU churn, more API calls handledâperfect for CodeBitâs readers.
php-fpm: The PHP Powerhouse
Whatâs php-fpm? FastCGI Process Managerâa real program, not just a protocol. Itâs the engine running my PHP API and chatting with nginx.
How It Works: php-fpm runs solo with a master and workers:
- Master: The dispatcher. Grabs requests from nginx and assigns themâlike picking who delivers what.
- Workers: The couriers. They process PHP and send back JSON or HTML.
- Smart Features: The master balances load, restarts crashed workers (e.g., memory hogs), and scales with traffic. After X requests, it refreshes workers to keep things smooth.
Neat Note: nginx uses a similar master-worker vibeâmore on that another day!
Hooking nginx to PHP
Letâs wire nginx to php-fpm for CodeBitâs API. Install it:
apt-get install php-fpmCheck itâs running:
systemctl status php8.2-fpm.service(Mineâs 8.2âyours might differ.)
Hereâs the nginx config with PHP support:
user webuser;
events {}
http {
include mime.types;
access_log /var/log/nginx/site_access.log;
error_log /var/log/nginx/site_errors.log;
server {
listen 80;
server_name 172.16.100.5;
root /srv/web/static/codebit;
index index.php index.html;
location / {
try_files $uri $uri/ =404;
}
location ~\.php {
include fastcgi.conf;
fastcgi_pass unix:/var/run/php/php-fpm.sock;
}
}
}CodeBit-Specific Breakdown
-
user webuser;
nginx runs aswebuserâa web server norm. -
index index.php index.html;
âTryindex.phpfor dynamic stuff, thenindex.htmlfor static.â No match? nginx shrugs. -
location / { try_files $uri $uri/ =404; }
Handles static assets:$uri: The path (e.g.,/styles.cssfromhttp://172.16.100.5/styles.css).$uri/: Checks folders (e.g.,/posts/grabsposts/index.htmlif there).=404: Nothing? 404!
Examples:http://172.16.100.5/about.htmlâ Serves the about page.http://172.16.100.5/snippetsâ Looks forsnippets/index.html.http://172.16.100.5/huhâ 404.
-
location ~\.php { ... }
Catches PHP files (likeapi/posts.php) with a regex (~\.phpmatches.phpendings):include fastcgi.conf;
Loads a file with FastCGI varsâlikeSCRIPT_FILENAMEâphp-fpmâs guide.fastcgi_pass unix:/var/run/php/php-fpm.sock;
Pipes PHP requests to php-fpm via a Unix socket (a fast data lane). Locate it:find / -name *fpm.sock
The Blog Flow
http://172.16.100.5/api/posts.phpâ nginx sees.php, hands it to php-fpm â php-fpm runs it, returns post data (e.g., JSON) â nginx passes it to Next.js â readers see fresh posts!
Bonus: nginx and CodeBitâs Next.js Frontend
For CodeBit Chronicles, Next.js handles both static and SSR pages. After next build, static files land in /out:
index.html(homepage)posts/[id].html(static post pages)- API calls to
/api/posts.phpfor dynamic data.
Hereâs nginx serving the Next.js frontend:
server {
listen 80;
server_name 172.16.100.6;
root /srv/web/static/codebit-front/out;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location /api/ {
proxy_pass http://172.16.100.5; # Points to PHP server
}
}root /srv/web/static/codebit-front/out;â Next.js static output.location / { try_files $uri $uri/ /index.html; }â Serves:- Exact files (e.g.,
/codebit.png). - Folders with
index.html(e.g.,/posts/123). - Falls to
index.htmlfor Next.js routing.
- Exact files (e.g.,
location /api/ { proxy_pass http://172.16.100.5; }â Forwards API calls to the PHP server.
This ties the frontend to the PHP backendâsmooth sailing for CodeBit!
Wrapping Up
From static pages to a PHP API powering CodeBit Chronicles, nginx, CGI, FastCGI, and php-fpm are my deployment heroes. nginx dishes out Next.js assets, while the CGI crew (led by php-fpm) fuels dynamic data. Whether itâs a blog post or a sleek frontend, they make it happen. Next time: Docker, tweaks, and optimizationâstay tuned!