Published on

Using Nginx for hosting PHP

Authors
  • avatar
    Name
    Loc Truong
    Twitter

Setup PHP and Nginx

sudo apt-get update
sudo apt-get install -y php8.1-fpm nginx php8.1-mysql php8.1-curl php8.1-gd php8.1-mbstring php8.1-xml php8.1-zip

Configure Nginx

sudo tee /etc/nginx/sites-available/default > /dev/null << 'EOF'
    server {
        listen 80;
        server_name _;
        root /var/www/html;
        index index.php index.html;

        # PHP application under /php-app
        location /php-app {
            alias /var/www/html/php-app;
            try_files $uri $uri/ /php-app/index.php?$args;

            location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_param SCRIPT_FILENAME $request_filename;
                fastcgi_pass unix:/run/php/php8.1-fpm.sock;
            }
        }
    }
    EOF

sudo systemctl restart nginx
sudo systemctl restart php8.1-fpm

Test PHP

mkdir /var/www/html/php-app/
sudo tee /var/www/html/php-app/index.php > /dev/null << 'EOF'
    <?php
    header('Content-Type: application/json');
    echo json_encode([
        'status' => 'success',
        'message' => 'PHP is working!',
        'php_version' => phpversion(),
        'server_time' => date('Y-m-d H:i:s')
    ]);
    EOF

Monitor logs

tail -f /var/log/nginx/access.log /var/log/nginx/error.log ngrok.log &
sleep 1h