Sub topic 1
How a request reaches your application
Prerequisites
This chapter assumes you can:
- Use the Linux command line and read file permissions.
- Edit files and install packages on a Debian or Ubuntu server.
- Read an HTTP request and response, including status codes and headers.
- Run a small PHP or Python web application, which later chapters deploy.
You do not need to know Nginx, PHP-FPM, or Gunicorn yet. This chapter builds the working model that the rest of the tutorial uses.
Why a web server sits in front of your application
A PHP script or a Python function can produce HTML, but it is a poor first point of contact for the internet. A dedicated web server such as Nginx handles tasks that an application runtime does badly or at high cost:
- Accepting thousands of slow or idle connections cheaply.
- Serving files such as images, CSS, and JavaScript without starting application code.
- Terminating HTTPS, so the application never handles certificates.
- Applying limits, logging, and access rules in one place.
The application then concentrates on what only it can do: run business logic, query a database, and build a dynamic response.
The path of one request
Follow a single request for https://example.com/blog/42.
- DNS lookup. The client resolves
example.comto your server's IP address. - TCP and TLS. The client connects to port 443 and completes a TLS handshake. Nginx holds the certificate and decrypts the traffic.
- HTTP parsing. Nginx reads the request line, headers, and body.
- Server selection. Nginx chooses a
serverblock by matching theHostheader againstserver_name. - Location selection. Inside that block, Nginx chooses a
locationby matching the URI. - Handling. Nginx either serves a file from disk or hands the request to the application.
- Response. The application's reply travels back through Nginx to the client. Nginx adds or rewrites some headers and writes an access log entry.
The key decision happens at step 6. Everything else in this tutorial is about how to make that handoff work and how to debug it when it fails.
Static and dynamic requests
A static request maps to a file that already exists, such as /images/logo.png. Nginx reads the file and sends it. No application code runs.
A dynamic request needs code to compute the answer, such as /blog/42 or /api/orders. Nginx cannot compute it, so it passes the request on.
Serving static files directly is faster and keeps application workers free. Application workers are a limited resource. If each one is busy sending a 2 MB image to a slow phone, it cannot handle the next real request.
Three ways to run application code
There are three common models for connecting a web server to application code. The model decides what you configure and what breaks.
| Model | How code runs | Typical example | Web server's role |
|---|---|---|---|
| Embedded module | Inside the web server process | Apache with `mod_php` | Runs the code itself |
| FastCGI | In separate, long-lived worker processes | Nginx with PHP-FPM | Forwards requests over the FastCGI protocol |
| Reverse proxy | In a separate HTTP-speaking server | Nginx with Gunicorn | Forwards requests as plain HTTP |
Embedded module
The language interpreter is loaded into each web server process. It is simple, but every web server process carries the interpreter, even when it is only serving an image. Nginx does not support this model for PHP or Python. It is the reason Apache setups behave differently from the Nginx setups in this tutorial.
FastCGI
The web server and the application run as separate processes. A pool manager, PHP-FPM for PHP, keeps a set of worker processes ready. Nginx sends each request over a socket in the FastCGI protocol, which carries the request's parameters (method, path, headers) as named variables. A worker runs the script and returns the output.
Reverse proxy
The application runs its own HTTP-capable server, and Nginx forwards requests to it as ordinary HTTP. Python applications use this model. A Python web framework does not speak HTTP directly. It follows an interface called WSGI (or ASGI for asynchronous code), and an application server such as Gunicorn translates between HTTP and that interface.
Both FastCGI and reverse proxy keep the web server and the application as separate programs. This brings three benefits:
- You can restart or upgrade the application without touching Nginx.
- The two can run as different users with different permissions.
- A crash in the application does not take down the web server.
A minimal working example
The Python case is easy to test in isolation. Start with a WSGI application, which is a callable that receives the request environment and a start_response function:
def application(environ, start_response):
body = b"Hello from WSGI\n"
start_response("200 OK", [
("Content-Type", "text/plain"),
("Content-Length", str(len(body))),
])
return [body]Save it as app.py, then run Gunicorn and test it before any web server is involved:
gunicorn --workers 3 --bind 127.0.0.1:8000 app:application
curl -i http://127.0.0.1:8000/The value app:application means "the object named application in the module app". If curl shows 200 OK and the body, the application layer works. Testing each layer on its own is the most useful debugging habit in this tutorial.
Now place Nginx in front. This server block serves /static/ files itself and proxies everything else:
server {
listen 80;
server_name example.com;
location /static/ {
alias /srv/myapp/static/;
}
location / {
proxy_pass http://unix:/run/gunicorn/app.sock;
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;
}
}Here /static/logo.png becomes a file read from /srv/myapp/static/logo.png. A request for /blog/42 matches the second location and goes to Gunicorn through a Unix socket. The proxy_set_header lines are needed because, without them, the application sees only Nginx as the client. Later chapters explain each directive.
Where a request can fail
Knowing the path tells you where to look when something breaks. The status code often points to the layer.
| Symptom | Likely layer | First thing to check |
|---|---|---|
| Connection refused or timeout | Network, firewall, or Nginx not running | `systemctl status nginx`, listening ports |
| 404 Not Found | Nginx file lookup or the application's routing | `root` or `alias` path, `location` match |
| 403 Forbidden | Nginx file permissions or an explicit deny rule | Directory permissions, `deny` rules |
| 502 Bad Gateway | Handoff between Nginx and the application | Is the app running? Does the socket path match? |
| 504 Gateway Timeout | Application too slow | Application logs, worker timeouts |
| 500 Internal Server Error | Application code | Application error log |
A 404 can come from two places. Nginx returns it when it cannot find a file. The application returns it when its own routing finds no match. The error page's styling often tells you which one answered.
The basic check cycle for any change is:
sudo nginx -t
sudo systemctl reload nginx
curl -I http://example.com/
sudo tail -n 20 /var/log/nginx/error.lognginx -t checks the syntax before you apply anything. reload applies the new configuration without dropping connections. curl -I shows only the response headers. The error log usually names the exact failure.
Common misunderstandings
- "Nginx runs my PHP." It does not. Nginx forwards the request, and PHP-FPM runs the script. If PHP-FPM is stopped, Nginx still serves static files but returns 502 for
.phpURLs. - "The app sees the real client." By default it sees Nginx at
127.0.0.1or a Unix socket. Forwarded headers fix this, as a later chapter covers. - "HTTPS reaches my app." With TLS termination, Nginx decrypts the traffic and the app receives plain HTTP. The app needs
X-Forwarded-Prototo know the original scheme. - "A 404 means the file is missing." It may mean a wrong
root, a wronglocation, or an application route that does not exist.
What the rest of the tutorial builds
The chapters that follow deal with each handoff in turn: Nginx basics, FastCGI and PHP-FPM, WSGI and Gunicorn, reverse proxying, systemd supervision, forwarded headers, TLS, permissions, logs, and tuning. Keep the request path from this chapter in mind. Each later configuration line belongs to one step of it.
Exercise
A site returns a styled 404 page for /images/logo.png, but it loads fine for /blog/42. Gunicorn is running. Which layer should you check first, and what would you look at?
Show answer
Check Nginx's static file handling first. Image requests should be served from disk by a location block, so look at its root or alias path and confirm the file exists at that exact path. The styled 404 suggests the request was forwarded to the application, which has no route for it. That means no static location matched, or the path in it is wrong.
Exercise
PHP pages return 502 Bad Gateway, but /static/style.css loads normally. What does this tell you about where the fault is, and what would you check?
Show answer
Static files are served by Nginx alone, so Nginx is running and its server block works. The fault is in the handoff to PHP-FPM or in PHP-FPM itself. Check that the PHP-FPM service is running and that the socket path in fastcgi_pass matches the socket PHP-FPM actually creates. Then read the Nginx error log for the exact message.