Ravindra BagaleCourses & study guides

9. PHP, LAMP and LEMP Step by Step

9.5 LEMP on Amazon Linux 2023

LEMP madhe Apache chya jaagi Nginx – static files Nginx swatah deto aani .php PHP-FPM la pathavto.

                        +------------------ EC2 (Linux) -------------------+
  Browser ──HTTP:80──►  |  Nginx ──FastCGI (unix socket)──► PHP-FPM        |
                        |    static files served directly      │           |
                        |                                      ▼           |
                        |                            MySQL/MariaDB :3306   |
                        +--------------------------------------------------+

Full LEMP installation

Amazon Linux 2023 (default Nginx server already handles .php via /etc/nginx/default.d/php.conf):

sudo yum install -y nginx php php-fpm php-mysqlnd php-gd php-mbstring php-xml mariadb105-server
sudo service nginx start
sudo service php-fpm start
sudo service mariadb start
sudo systemctl enable nginx php-fpm mariadb
sudo mysql_secure_installation
echo "<?php phpinfo();" | sudo tee /usr/share/nginx/html/info.php
curl -s http://localhost/info.php | grep -m1 "PHP Version"

Your own Nginx server block for a PHP app (/etc/nginx/conf.d/phpapp.conf):

sudo mkdir -p /var/www/phpapp
sudo tee /etc/nginx/conf.d/phpapp.conf > /dev/null <<'EOF'
server {
    listen 80;
    server_name YOUR_SERVER_NAME;
    root /var/www/phpapp;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/run/php-fpm/www.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}
EOF
sudo sed -i "s/YOUR_SERVER_NAME/$(curl -s https://checkip.amazonaws.com)/" /etc/nginx/conf.d/phpapp.conf
sudo nginx -t && sudo service nginx reload

Why this matters for security

try_files $uri =404; inside the PHP location stops Nginx from passing non-existent paths to PHP – an old misconfiguration let attackers execute uploaded images as PHP (/uploads/cat.jpg/x.php). Small config lines like this close real attack paths.

Ravindra Bagale's Tip

info.php (phpinfo) test sathi banavla aani visarla – khup students chya servers var he mahine-mahine rahta. Tyat PHP version, paths, modules sagla disto – attacker sathi khajina! Test zala ki laghech sudo rm kara.

Lab

Build LEMP on Amazon Linux, create the phpapp server block and confirm a PHP page runs from /var/www/phpapp.