CodeBlanks Logo Icon CodeBlanks

Nginx configuration

PHP course · Expert · Lesson 45/54

Learn to configure Nginx with PHP-FPM as a reverse proxy.

Nginx and fastcgi_pass

Nginx hands the incoming HTTP request to PHP-FPM via fastcgi_pass. fastcgi_pass 127.0.0.1:9000 points to a local FPM, fastcgi_pass unix:/var/run/php-fpm.sock to a UNIX socket.

The location ~ \.php$ block sends only paths ending with .php to FPM. fastcgi_param SCRIPT_FILENAME declares the full path of the file to run.

include fastcgi_params loads common parameters; it saves you from declaring each one by hand.

SCRIPT_FILENAME and root

Without the SCRIPT_FILENAME parameter FPM cannot tell which file to run. $document_root$fastcgi_script_name builds the full path.

root /var/www/html is the document root; index index.php names the default file. try_files $uri =404 returns 404 when the file is missing.

Together these three directives route both static files and PHP scripts correctly; a wrong setting yields File not found.

Exercise Generate an nginx server block

Build an nginx server block text with PHP: a location ~ \.php$ block containing fastcgi_pass 127.0.0.1:9000;, fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; and include fastcgi_params;. Write it to nginx.conf via file_put_contents and echo the text.

Show example solution
Build $nginx with single-quoted parts joined by "\n". Use single quotes so $document_root is not interpolated. Then add file_put_contents("nginx.conf", $nginx); and echo $nginx;.
Example solution:
<?php
// Generate nginx server block
$nginx = 'location ~ \\.php$ {' . "\n" .
    '    fastcgi_pass 127.0.0.1:9000;' . "\n" .
    '    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;' . "\n" .
    '    include fastcgi_params;' . "\n" .
    '}' . "\n";
file_put_contents("nginx.conf", $nginx);
echo $nginx;

Test yourself

  1. Which Nginx directive forwards a request to PHP-FPM?

    • proxy_pass
    • root
    • fastcgi_pass
    • try_files
    Show answer

    fastcgi_pass — Correct. fastcgi_pass hands the request to PHP-FPM over the FastCGI protocol.

  2. Complete the fastcgi_pass line

    <?php
    $nginx = "location ~ \\.php$ {\n    ____ 127.0.0.1:9000;\n    include fastcgi_params;\n}";
    print_r(["nginx" => $nginx]);
    
    Show answer
    <?php
    $nginx = "location ~ \\.php$ {\n    fastcgi_pass 127.0.0.1:9000;\n    include fastcgi_params;\n}";
    print_r(["nginx" => $nginx]);
    
  3. Match the Nginx directives

    fastcgi_pass
    Forwards to PHP-FPM
    fastcgi_param
    Sends a parameter
    root
    Document root directory
    try_files
    Tries file existence

All lessons in Expert