RDM LABSPORTUGUÊS

Technical article/ · 8 min read

NGINX, web servers and the path to PHP

Laravel Saga · Season 0 · Episode 02

In the previous episode, we saw that an HTTP request is a text message that leaves the browser and crosses the internet. Today I want to answer the question left hanging: who receives that message on the other side?

I'll give you the spoiler right away: it isn't PHP. Between the internet and your code there's an intermediary called a web server. And I can say, from experience, that understanding this intermediary is what separates someone who spends hours staring at a 502 error without knowing what to do from someone who solves the problem in five minutes.

What is a web server, anyway

A web server is a program that "listens" on a network port (80 for HTTP, 443 for HTTPS), accepts connections, reads HTTP messages and sends back responses. The names you'll hear most are NGINX, Apache, Caddy and, more recently in the PHP world, FrankenPHP.

But a modern web server does much more than just receive requests. It usually takes on several jobs:

JobWhat it does
Serving static filesDelivers CSS, JS, images and fonts straight from disk, very quickly
Reverse proxyPasses requests on to another application (PHP-FPM, Node, Octane)
TLS terminationHandles HTTPS encryption so the application doesn't have to
Load balancingSpreads requests across several application servers
Compression and cachingCompresses responses (gzip, brotli) and keeps copies
ProtectionLimits upload size and request rate, blocks sensitive paths

Why NGINX became the standard

A bit of history helps here. NGINX was born in 2004 to solve a problem that became known as C10K: how do you serve 10,000 simultaneous connections on a single server?

Apache's classic model (prefork) created one process per connection. Ten thousand connections meant ten thousand processes, each taking up memory, even if most of them were just waiting for a slow client to finish sending data.

NGINX took another route: an event-driven architecture. It uses a few worker processes (usually one per CPU core), and each one manages thousands of connections at the same time, acting only when one of them has something to do. The result is low, predictable memory usage.

10,000 connectionsthe same server
Apache preforkone process per connection
  • process · connection 1
  • process · connection 2
  • process · connection 3
  • …
NGINXevent-driven
worker 1
  • connections 1 to 5000
worker 2
  • connections 5001 to 10000
One process per connection or a few workers for all of them

To be fair to Apache: modern versions also have an event-based model (mpm_event), so the difference today is much smaller than it once was. Even so, NGINX became the de facto standard for PHP applications in production, and it's what Laravel Forge configures by default.

The detail that confuses everyone: NGINX doesn't run PHP

If you keep only one thing from this episode, let it be this. NGINX knows how to serve files, but it can't run a single line of PHP. For that, it talks to another program: PHP-FPM (FastCGI Process Manager).

That conversation happens over a protocol called FastCGI, through a Unix socket (a special file on disk) or a TCP port. Here's the full path:

The path of a request to PHPBrowser to NGINX: HTTPS. NGINX to public/, when file exists? NGINX to PHP-FPM: FastCGI · unix socket. PHP-FPM to index.php: runs. Scenario GET /posts/42: Dynamic request. There is no /posts/42 file in public/, so try_files hands over to index.php. NGINX passes it to PHP-FPM over FastCGI and the response comes back the same way. Path: Browser, NGINX, PHP-FPM, index.php. Hint: try_files $uri $uri/ /index.php?$query_string;. Scenario GET /css/app.css: Static file. The file exists in public/. NGINX serves it straight from disk and PHP never hears about the request. Path: Browser, NGINX, public/. Scenario 502: Bad Gateway. NGINX tried to reach PHP-FPM and could not. The service may be stopped, the socket may have another name or a permission may be missing. Path: Browser, NGINX. NGINX to PHP-FPM failing. PHP-FPM down. Hint: systemctl status php8.4-fpm · ls -la /run/php/. Scenario 504: Gateway Timeout. PHP-FPM took the request, but the code ran for too long. NGINX gives up waiting and responds with an error. Path: Browser, NGINX, PHP-FPM. PHP-FPM to index.php slow. index.php slow. Hint: a slow query in the code · fastcgi_read_timeout.BrowserclientNGINXweb serverpublic/static filePHP-FPMprocess managerindex.phpfront controllerHTTPSfile exists?FastCGI · unix socketrunsBrowserclientNGINXweb serverPHP-FPMprocess managerindex.phpfront controllerHTTPSFastCGI · unix socketrunsBrowserclientNGINXweb serverpublic/static fileHTTPSfile exists?BrowserclientNGINXweb serverPHP-FPMprocess managerHTTPSFastCGI · unix socketBrowserclientNGINXweb serverPHP-FPMprocess managerindex.phpfront controllerHTTPSFastCGI · unix socketruns
The path of a request to PHPBrowser to NGINX: HTTPS. NGINX to public/, when file exists? NGINX to PHP-FPM: FastCGI · unix socket. PHP-FPM to index.php: runs. Scenario GET /posts/42: Dynamic request. There is no /posts/42 file in public/, so try_files hands over to index.php. NGINX passes it to PHP-FPM over FastCGI and the response comes back the same way. Path: Browser, NGINX, PHP-FPM, index.php. Hint: try_files $uri $uri/ /index.php?$query_string;. Scenario GET /css/app.css: Static file. The file exists in public/. NGINX serves it straight from disk and PHP never hears about the request. Path: Browser, NGINX, public/. Scenario 502: Bad Gateway. NGINX tried to reach PHP-FPM and could not. The service may be stopped, the socket may have another name or a permission may be missing. Path: Browser, NGINX. NGINX to PHP-FPM failing. PHP-FPM down. Hint: systemctl status php8.4-fpm · ls -la /run/php/. Scenario 504: Gateway Timeout. PHP-FPM took the request, but the code ran for too long. NGINX gives up waiting and responds with an error. Path: Browser, NGINX, PHP-FPM. PHP-FPM to index.php slow. index.php slow. Hint: a slow query in the code · fastcgi_read_timeout.BrowserclientNGINXweb serverpublic/static filePHP-FPMprocess managerindex.phpfront controllerHTTPSexists?FastCGIrunsBrowserclientNGINXweb serverPHP-FPMprocess managerindex.phpfront controllerHTTPSFastCGIrunsBrowserclientNGINXweb serverpublic/static fileHTTPSexists?BrowserclientNGINXweb serverPHP-FPMprocess managerHTTPSFastCGIBrowserclientNGINXweb serverPHP-FPMprocess managerindex.phpfront controllerHTTPSFastCGIruns

GET /posts/42

Dynamic request

There is no /posts/42 file in public/, so try_files hands over to index.php. NGINX passes it to PHP-FPM over FastCGI and the response comes back the same way.

try_files $uri $uri/ /index.php?$query_string;

GET /css/app.css

Static file

The file exists in public/. NGINX serves it straight from disk and PHP never hears about the request.

502

Bad Gateway

NGINX tried to reach PHP-FPM and could not. The service may be stopped, the socket may have another name or a permission may be missing.

systemctl status php8.4-fpm · ls -la /run/php/

504

Gateway Timeout

PHP-FPM took the request, but the code ran for too long. NGINX gives up waiting and responds with an error.

a slow query in the code · fastcgi_read_timeout

The path of a request to PHP

And now those two mysterious errors make perfect sense:

  • 502 Bad Gateway: NGINX tried to talk to PHP-FPM and couldn't. The service may be stopped, the socket may have the wrong name or a permission may be missing.
  • 504 Gateway Timeout: PHP-FPM received the request, but took too long to respond.

So, next time you see one of these two, you'll know: the problem is almost never in your Laravel code. It's in the communication between NGINX and PHP-FPM.

Reading an NGINX configuration for Laravel, line by line

This is a typical configuration, very close to the one the Laravel documentation recommends:

nginxserver {
    listen 80;
    listen [::]:80;
    server_name myblog.com;
    root /var/www/myblog/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;
    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ ^/index\.php(/|$) {
        fastcgi_pass unix:/run/php/php8.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_hide_header X-Powered-By;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

At first glance it looks like a lot, but only a few lines really matter. Let's go through them.

root /var/www/myblog/public;

Notice that the public root points to the public/ folder, and not to the project root. That's a fundamental security decision. Files like .env (with the database passwords), composer.json and all your source code stay out of the browser's reach. If the root pointed to the project root, anyone could type myblog.com/.env and read your credentials. Yes, this happens more than it should.

try_files $uri $uri/ /index.php?$query_string;

This is, by far, the most important line. It tells NGINX, in this order:

  1. Is there a file at this path? Then serve it. (/css/app.css becomes public/css/app.css)
  2. Is there a folder at this path? Try to serve it.
  3. Nothing of the sort? Then pass it on to /index.php, keeping the query string.

Think of the address /posts/42?ref=home. There's no file or folder with that name, so it ends up at index.php. That's how a single PHP file can handle every URL in the application. This pattern has a name, Front Controller, and it's the starting point of the saga's first chapter.

location ~ ^/index\.php(/|$)

Here only index.php is passed on to PHP-FPM. Why? Imagine someone manages to upload a malicious .php file to public/uploads/. With this rule, it will never be executed. Old configurations used location ~ \.php$, which executes any PHP file. If you come across that on a server, change it.

fastcgi_param SCRIPT_FILENAME ...

This line tells PHP-FPM which file to execute. $realpath_root resolves symbolic links, which makes a difference in zero-downtime deploys, which switch a link called current to point to the new version of the code.

location ~ /\.(?!well-known).*

Blocks hidden files, such as .git and .env, but allows the .well-known folder, which Let's Encrypt uses to issue certificates.

HTTPS and proxies in front of the application

In production, it's common for NGINX itself to handle HTTPS:

nginxserver {
    listen 443 ssl;
    http2 on;
    server_name myblog.com;

    ssl_certificate     /etc/letsencrypt/live/myblog.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/myblog.com/privkey.pem;

    # ... the rest the same as the previous configuration
}

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

Now, pay attention to a situation that catches a lot of people out. When there's one more intermediary in front of your server (Cloudflare, or an AWS load balancer), the application receives the request from the proxy, not from the user. The IP it sees is the proxy's, and the protocol may look like HTTP even though the user came in over HTTPS.

To solve this, the proxy passes on the original data in the X-Forwarded-For and X-Forwarded-Proto headers, the ones we saw in the previous episode. The application has to be configured to trust these headers, but only when they come from known proxies. In Laravel, that's the job of the TrustProxies middleware, and you'll meet it again in the saga.

What the application sees behind a proxy1. Browser to Cloudflare: HTTPS, IP 200.1.2.3. 2. Cloudflare to NGINX: HTTP, X-Forwarded-*. 3. NGINX to Laravel: passes the headers on. 4. Laravel: trust this proxy? 5. Laravel replies to NGINX: links with https://. 6. NGINX replies to Cloudflare: response. 7. Cloudflare replies to Browser: response.Browserthe userCloudflareproxyNGINXweb serverLaravelTrustProxiesHTTPS, IP 200.1.2.3HTTP, X-Forwarded-*passes the headers ontrust this proxy?links with https://responseresponse
What the application sees behind a proxy

Want a classic symptom of a misconfigured proxy? Laravel generates http:// links on a page served over HTTPS, and the browser blocks the CSS and JavaScript as mixed content. If that ever happens to you, you'll know where to start.

What about Apache, Caddy and FrankenPHP?

NGINX isn't the only option, and the alternatives are worth knowing.

Apache works very well with Laravel. In fact, the project already ships with a public/.htaccess file with rules equivalent to try_files. The difference is that .htaccess is read on every request, which has a small cost; in NGINX, the configuration is loaded only once.

Caddy is a modern server that sets up HTTPS automatically with Let's Encrypt. The configuration for Laravel fits in a few lines.

And FrankenPHP is the most interesting one for this series. It's built on Caddy and embeds PHP inside the server itself, with no PHP-FPM. It also has a "worker mode", in which the application stays loaded in memory between one request and the next. FrankenPHP is one of Laravel Octane's options, and in the next episode you'll understand why that changes so much.

Two processes or just oneBrowser to NGINX: traditional. NGINX to PHP-FPM: FastCGI. PHP-FPM to index.php: runs. Browser to FrankenPHP: FrankenPHP. FrankenPHP to index.php: in the same process. Scenario Traditional. NGINX receives the request and passes it on to PHP-FPM over FastCGI. Two programs talking through a socket. Path: Browser, NGINX, PHP-FPM, index.php. Scenario FrankenPHP. The web server and PHP live in the same process. In worker mode, the application also stays loaded in memory. Path: Browser, FrankenPHP, index.php.BrowserclientNGINXweb serverPHP-FPManother processFrankenPHPserver + PHPindex.phpthe applicationtraditionalFastCGIrunsFrankenPHPin the same processBrowserclientNGINXweb serverPHP-FPManother processindex.phpthe applicationtraditionalFastCGIrunsBrowserclientFrankenPHPserver + PHPindex.phpthe applicationFrankenPHPin the same process
Two processes or just oneBrowser to NGINX: traditional. NGINX to PHP-FPM: FastCGI. PHP-FPM to index.php: runs. Browser to FrankenPHP: FrankenPHP. FrankenPHP to index.php: in the same process. Scenario Traditional. NGINX receives the request and passes it on to PHP-FPM over FastCGI. Two programs talking through a socket. Path: Browser, NGINX, PHP-FPM, index.php. Scenario FrankenPHP. The web server and PHP live in the same process. In worker mode, the application also stays loaded in memory. Path: Browser, FrankenPHP, index.php.BrowserclientNGINXweb serverPHP-FPManother processFrankenPHPserver + PHPindex.phpthe applicationtraditionalFastCGIrunsFrankenPHP1 processBrowserclientNGINXweb serverPHP-FPManother processindex.phpthe applicationtraditionalFastCGIrunsBrowserclientFrankenPHPserver + PHPindex.phpthe applicationFrankenPHP1 process

Traditional

NGINX receives the request and passes it on to PHP-FPM over FastCGI. Two programs talking through a socket.

FrankenPHP

The web server and PHP live in the same process. In worker mode, the application also stays loaded in memory.

Two processes or just one

Commands to keep at hand

bashsudo nginx -t                      # validates the configuration syntax
sudo systemctl reload nginx        # applies changes without dropping connections
sudo systemctl status php8.4-fpm   # is PHP-FPM running?

sudo tail -f /var/log/nginx/error.log   # NGINX errors (the 502s show up here)
sudo tail -f /var/log/nginx/access.log  # every request received

ls -la /run/php/                   # which PHP-FPM socket actually exists?

A piece of advice from someone who has taken a site down by accident: always run nginx -t before reloading. A syntax error followed by a restart takes the site offline. A reload after a successful -t doesn't break anything.

What to take into the saga

  • The web server receives the request and decides whether to serve a file or pass it on to PHP.
  • NGINX doesn't run PHP; it talks to PHP-FPM over FastCGI.
  • The public root is the public/ folder, and try_files turns every unknown URL into a call to index.php.
  • 502 and 504 are communication problems between the web server and PHP, not problems in your code.
  • When there are proxies along the way, you need to configure trust in the X-Forwarded-* headers.

Next episode

NGINX handed the request to PHP-FPM, which will run index.php. But what happens in there? Why does PHP "forget" absolutely everything between one request and the next? And why is that, at the same time, the language's greatest strength and greatest weakness?

That's what we'll find out in the next episode, when we open up the PHP engine. See you in episode 03.

References and further reading

Official documentation

Going deeper