DEV Community

Manoj Swami
Manoj Swami

Posted on

Setting Up a PHP Website on EC2 with Nginx, MySQL, PHP, and Git

This guide will walk you through the process of setting up a PHP website on an Amazon EC2 instance using Nginx as the web server, MySQL as the database, PHP for server-side scripting, and Git for version control. We'll cover everything from initial setup to troubleshooting common issues.

Table of Contents

  1. Launch an EC2 Instance
  2. Connect to Your EC2 Instance
  3. Update and Upgrade the System
  4. Install Nginx
  5. Install MySQL
  6. Install PHP
  7. Install Git
  8. Configure Nginx
  9. Set Up Your Website Directory
  10. Clone Your Repository
  11. Set Correct Permissions
  12. Configure PHP
  13. Set Up SSL (Optional but Recommended)
  14. Troubleshooting Common Issues
  15. Best Practices and Security Considerations

1. Launch an EC2 Instance

  1. Log in to your AWS Management Console.
  2. Navigate to EC2 and click "Launch Instance".
  3. Choose an Ubuntu Server AMI (e.g., Ubuntu Server 22.04 LTS).
  4. Select an instance type (t2.micro is eligible for free tier).
  5. Configure instance details, add storage, and tags as needed.
  6. Configure security group to allow SSH (port 22), HTTP (port 80), and HTTPS (port 443) traffic.
  7. Review and launch the instance, selecting or creating a key pair.

2. Connect to Your EC2 Instance

Use SSH to connect to your instance:

ssh -i /path/to/your-key.pem ubuntu@your-instance-public-dns
Enter fullscreen mode Exit fullscreen mode

Replace /path/to/your-key.pem with the path to your key file and your-instance-public-dns with your instance's public DNS name.

3. Update and Upgrade the System

Once connected, update and upgrade your system:

sudo apt update
sudo apt upgrade -y
Enter fullscreen mode Exit fullscreen mode

4. Install Nginx

Install Nginx web server:

sudo apt install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx
Enter fullscreen mode Exit fullscreen mode

Verify Nginx is running:

sudo systemctl status nginx
Enter fullscreen mode Exit fullscreen mode

5. Install MySQL

Install MySQL server:

sudo apt install mysql-server -y
sudo systemctl start mysql
sudo systemctl enable mysql
Enter fullscreen mode Exit fullscreen mode

Secure your MySQL installation:

sudo mysql_secure_installation
Enter fullscreen mode Exit fullscreen mode

Follow the prompts to set a root password and remove insecure default settings.

6. Install PHP

We'll install PHP 8.1 (or the latest stable version available in the Ubuntu repositories):

sudo apt install php8.1-fpm php8.1-mysql php8.1-common php8.1-cli php8.1-curl php8.1-mbstring php8.1-xml php8.1-zip -y
Enter fullscreen mode Exit fullscreen mode

Verify PHP installation:

php -v
Enter fullscreen mode Exit fullscreen mode

7. Install Git

Install Git for version control:

sudo apt install git -y
Enter fullscreen mode Exit fullscreen mode

Verify Git installation:

git --version
Enter fullscreen mode Exit fullscreen mode

8. Configure Nginx

Create a new Nginx server block configuration:

sudo nano /etc/nginx/sites-available/your_domain
Enter fullscreen mode Exit fullscreen mode

Add the following configuration (replace your_domain with your actual domain or IP address):

server {
    listen 80;
    server_name your_domain www.your_domain;
    root /var/www/your_domain;
    index index.php index.html index.htm;

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

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }
}
Enter fullscreen mode Exit fullscreen mode

Enable the new site:

sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/
Enter fullscreen mode Exit fullscreen mode

Test Nginx configuration:

sudo nginx -t
Enter fullscreen mode Exit fullscreen mode

If the test is successful, reload Nginx:

sudo systemctl reload nginx
Enter fullscreen mode Exit fullscreen mode

9. Set Up Your Website Directory

Create the web root directory:

sudo mkdir -p /var/www/your_domain
sudo chown -R $USER:$USER /var/www/your_domain
sudo chmod -R 755 /var/www/your_domain
Enter fullscreen mode Exit fullscreen mode

10. Clone Your Repository

If you have an existing Git repository for your website, clone it into your web root:

cd /var/www/your_domain
git clone https://github.com/your-username/your-repo.git .
Enter fullscreen mode Exit fullscreen mode

Replace https://github.com/your-username/your-repo.git with your actual repository URL.

If you're starting a new project, initialize a new Git repository:

cd /var/www/your_domain
git init
Enter fullscreen mode Exit fullscreen mode

11. Set Correct Permissions

Set the correct permissions for your web files:

sudo chown -R www-data:www-data /var/www/your_domain
sudo find /var/www/your_domain -type d -exec chmod 755 {} \;
sudo find /var/www/your_domain -type f -exec chmod 644 {} \;
Enter fullscreen mode Exit fullscreen mode

To allow the Ubuntu user to manage files:

sudo usermod -a -G www-data ubuntu
sudo chmod g+s /var/www/your_domain
Enter fullscreen mode Exit fullscreen mode

You may need to log out and log back in for the group changes to take effect.

12. Configure PHP

Adjust PHP settings if needed:

sudo nano /etc/php/8.1/fpm/php.ini
Enter fullscreen mode Exit fullscreen mode

Common settings to adjust:

upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 300
memory_limit = 256M
Enter fullscreen mode Exit fullscreen mode

After making changes, restart PHP-FPM:

sudo systemctl restart php8.1-fpm
Enter fullscreen mode Exit fullscreen mode

13. Set Up SSL (Optional but Recommended)

To secure your website with HTTPS, you can use Let's Encrypt:

sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d your_domain -d www.your_domain
Enter fullscreen mode Exit fullscreen mode

Follow the prompts to set up SSL.

14. Troubleshooting Common Issues

Permission Denied Errors

If you encounter "Permission denied" errors in Nginx error logs:

  1. Check file ownership:
   ls -l /var/www/your_domain
Enter fullscreen mode Exit fullscreen mode
  1. Ensure Nginx is running as the correct user:
   ps aux | grep nginx
Enter fullscreen mode Exit fullscreen mode
  1. Check Nginx configuration:
   sudo nano /etc/nginx/nginx.conf
Enter fullscreen mode Exit fullscreen mode

Ensure the user is set to www-data.

PHP Errors

For PHP-related errors:

  1. Check PHP-FPM logs:
   sudo tail -f /var/log/php8.1-fpm.log
Enter fullscreen mode Exit fullscreen mode
  1. Ensure PHP-FPM is running:
   sudo systemctl status php8.1-fpm
Enter fullscreen mode Exit fullscreen mode
  1. Verify PHP-FPM socket file exists:
   ls /var/run/php/php8.1-fpm.sock
Enter fullscreen mode Exit fullscreen mode

Git Issues

If you encounter Git permission issues:

  1. Ensure the .git directory is owned by your user:
   sudo chown -R ubuntu:ubuntu /var/www/your_domain/.git
Enter fullscreen mode Exit fullscreen mode
  1. Use sudo for Git operations or temporarily change ownership:
   sudo chown -R ubuntu:ubuntu /var/www/your_domain
   git pull
   sudo chown -R www-data:www-data /var/www/your_domain
Enter fullscreen mode Exit fullscreen mode

15. Best Practices and Security Considerations

  1. Regularly update your system and software:
   sudo apt update && sudo apt upgrade -y
Enter fullscreen mode Exit fullscreen mode
  1. Use strong passwords for all services (MySQL, SSH, etc.).

  2. Configure a firewall (e.g., UFW) to restrict incoming traffic:

   sudo ufw allow OpenSSH
   sudo ufw allow 'Nginx Full'
   sudo ufw enable
Enter fullscreen mode Exit fullscreen mode
  1. Implement fail2ban to protect against brute-force attacks:
   sudo apt install fail2ban -y
   sudo systemctl start fail2ban
   sudo systemctl enable fail2ban
Enter fullscreen mode Exit fullscreen mode
  1. Regularly backup your website and database.

  2. Monitor your server logs for unusual activity:

   sudo tail -f /var/log/nginx/access.log
   sudo tail -f /var/log/nginx/error.log
Enter fullscreen mode Exit fullscreen mode
  1. Use version control (Git) for all your code changes.

  2. Implement proper error handling and logging in your PHP application.

  3. Use prepared statements or ORM to prevent SQL injection attacks.

  4. Keep your application dependencies up-to-date and use a dependency manager like Composer for PHP projects.

By following this guide, you should have a fully functional PHP website running on an EC2 instance with Nginx, MySQL, and Git.
Remember to adapt the instructions to your specific needs and always prioritize security in your setup.

Top comments (1)

Collapse
 
koas profile image
Koas

Very detailed list, congrats! I'd suggest setting up a PHP debugger / logger like XDebug or bcons for easier detection of PHP related issues.

Also, while regular database backup is of course mandatory, those backups won't be available if there is any problem with the instance storage. I'd add an additional step to set up automatic sync of the DB backups folder to an S3 bucket (using AWS CLI is just a matter of adding a line to the crontab file).