Sub topic 1
How a request reaches your application
Prerequisites
This chapter assumes you know basic Linux commands, can edit files with root access on a Debian or Ubuntu server, and understand HTTP requests, status codes, and headers. You do not need to run anything yet.
The path of one request
A browser sends an HTTP request to your server's address on port 80 or 443. The web server, Nginx in this tutorial, receives it first. Nginx either answers from a file on disk or forwards the request to your application. The application builds a response, Nginx returns it, and the browser displays the page.
Three models for running application code
Web servers use one of three models to run application code.
- Embedded: the code runs inside the web server process, as an Apache module does. Nginx does not use this model for PHP or Python in a typical setup.
- FastCGI: Nginx sends the request to a separate process manager, such as PHP-FPM, using the FastCGI protocol.
- Reverse proxy: Nginx forwards the whole HTTP request to an application server that speaks HTTP, such as Gunicorn for Python.
Nginx basics: server blocks, root, and locations
A server block is a section of Nginx configuration that handles requests for one site. Nginx selects it by port and server_name. The root directive sets the folder that holds the site's files. A location block matches part of the request path and sets how to handle it.
server {
listen 80;
server_name example.com;
root /var/www/example/public;
location / {
try_files $uri $uri/ =404;
}
}Static versus dynamic content
Static files, such as images, CSS, and JavaScript, are sent to the browser unchanged. Nginx serves these faster than an application can, so let Nginx handle them. Dynamic requests need code to run, so Nginx passes them to the application. Use one location block for static paths and another for everything else.
Unix sockets or TCP ports
Nginx and the application need a shared connection point. A TCP port, such as 127.0.0.1:8000, works over the network stack and can reach other hosts. A Unix socket, such as /run/php/php8.3-fpm.sock, is a file on the same machine. It skips the network stack and follows file permissions. On a single server, a Unix socket is usually the better choice.
Exercise
A location block for /static/ sets alias /srv/app/static/. A request for /static/logo.png arrives. Which file does Nginx read?
Show answer
/srv/app/static/logo.png. The alias directive replaces the matched location prefix with the given path.