Set up a PHP 8.1/PHP 8.2 AWS EC2 Linux 2 server
Learn how to set up an AWS EC2 Linux 2 server with PHP 8.1, PHP 8.2, or PHP 8.3, Apache (httpd), HTTPS (SSL), DNS, Putty, and Filezilla.
Setting up your EC2 instance
Setting up an Amazon EC2 instance is a cornerstone task for any developer or system administrator working with AWS. It allows you to deploy, manage, and scale applications in the AWS cloud environment. Whether you're looking to host a website, run a large database, or process large amounts of data, EC2 provides the flexibility and scalability needed. Below are the detailed steps to get your EC2 instance up and running:
- Log in to AWS Management Console: Access the console at https://aws.amazon.com/console/ and log in with your credentials.
- Select EC2 from Services: In the AWS Management Console, find and select EC2 under the Compute section.
- Launch Instance: Click on the Launch Instance button to start the setup process.
- Choose an Amazon Machine Image (AMI): In this tutorial we're using the Amazon Linux 2 AMI (HVM)
- Select an Instance Type: Choose the appropriate instance type based on the CPU, memory, and storage needs of your application.
- Configure Instance: Set the number of instances, network, and subnet settings. You can leave these as default for basic setups.
- Add Storage: Adjust the size and type of storage to meet your requirements.
- Configure Security Group: Set up the firewall rules for your instance. Ensure to allow SSH (port 22) for our Linux instance.
- Review and Launch: Review your instance configuration and make any necessary changes.
- Create a Key Pair: Before launching, create a new key pair or select an existing one. Download and safely store the key pair, as it's required to access the instance (we'll use this later.)
- Launch Instance: Click the Launch button to start your instance.
Following these steps will have your Amazon EC2 instance up and running. It's essential to keep in mind the security and cost implications of running an EC2 instance. Regularly monitor and optimize your setup to ensure it remains secure, efficient, and cost-effective.
Set up an elastic IP address (optional)
Setting up an Elastic IP address for your Amazon EC2 instance is an important step to ensure that your instance has a static, public IP address. This is crucial for hosting websites, running web servers, or any application that requires a stable IP address. Unlike the default public IP address that changes every time you stop and restart your instance, an Elastic IP address remains the same, providing a consistent endpoint for your applications. Here’s how you can set up an Elastic IP address in AWS:
- Log in to AWS Management Console: Access your AWS account by logging in at https://aws.amazon.com/console/.
- Open the Amazon EC2 console: Navigate to the EC2 dashboard within the AWS Management Console.
- Allocate Elastic IP Address: In the EC2 dashboard, go to the Network & Security section and click on Elastic IPs. Then, click on Allocate Elastic IP address.
- Configure Elastic IP Address: Follow the on-screen instructions to allocate a new IP address. You may choose to allocate from Amazon's pool of IP addresses or bring your own IP address (BYOIP).
- Associate Elastic IP Address: Once allocated, select the Elastic IP and click on Actions, then Associate Elastic IP address. Choose the instance we created in the precious section to assign the Elastic IP and select the private IP address to associate with it, if applicable.
- Confirm Association: Review your selections and click Associate to apply the Elastic IP address to your selected EC2 instance.
By following these steps, you will have successfully assigned an Elastic IP address to your EC2 instance, ensuring a stable and persistent public IP address for your applications. Remember, while Elastic IPs are free as long as they are associated and used, AWS charges for Elastic IPs that are allocated but not associated with a running instance.
Setting up DNS records
Setting up DNS (Domain Name System) records is essential for linking your domain name to your website hosted on an Amazon EC2 instance. DNS records act as a roadmap for internet traffic, directing users to your website when they enter your domain name into their browser. Proper configuration of DNS records is crucial for your website’s accessibility and performance.
In this tutorial we assume that you've already registered a domain name and are ready to set up the DNS records. Here is what to put where:
Type: A
Name: website.com
IPv4 address: [Your elastic IP or your EC2 instance's public IP address]
TTL: Auto or as per your preference
# Make the www subdomain point to your main site
Type: CNAME
Name: www
Target: website.com
TTL: Auto or as per your preference
Properly setting up DNS records is key to ensuring that your domain correctly points to your EC2-hosted website. It’s a straightforward process that significantly impacts your site’s accessibility and reliability. Your server should now be accessible by browsing to your domain name. Note: adding to or changing the DNS records mike take some time to propagate throughout the internet.
Connecting PuTTY through SSH to EC2
Connecting PuTTY to your Amazon EC2 instance is a straightforward process that allows you to remotely manage your server. PuTTY, a popular SSH and telnet client, is widely used for accessing servers hosted on AWS. To establish a connection, you'll need the Elastic IP or public instance IP of your EC2 instance and the private key file (with a .ppk extension) for authentication. Here’s a step-by-step guide to setting up a connection using PuTTY:
- Open PuTTY: Launch PuTTY on your computer. If you don’t have PuTTY installed, you can download it from https://www.putty.org/.
- Configure Connection Details:
- When you just opened PuTTY, it should have opened the tab Session. Put the following data there:
- Host Name 'or IP address: Enter the Elastic IP or public instance IP of your EC2 instance ec2-XX-XX-XX-XX.compute-1.amazonaws.com.
- Port: 22
- Connection type: Choose SSH and Telnet in the drop-down
- Now go to Connections > SSH > Auth > Credentials
- Locate your .ppk file (key pair) that you've downloaded when creating your EC2 instance, if it is not in the .pkk format then you'll have to convert it using PuTTYgen.
- Add the path to the .pkk file to the Private key file for authentication input field.
- Go back to Session
- Provide a name for this connection to your instance in the Saved Sessions input field.
- Click on the Save button.
- Whenever opening PuTTY now you'll just have to click on your connection name in the and click on load to load the settings of this connection.
- Click on the Open button to connect.
- When you just opened PuTTY, it should have opened the tab Session. Put the following data there:
- Log into your instance: After a connection is made in the console window, it will ask which user you want to log in with, use ec2-user.
By now you will have establish a secure SSH connection to your EC2 instance using PuTTY. This method ensures easy and secure access to your cloud server, enabling efficient remote management and administration.
Connecting FileZilla through SFTP/SSH to EC2
Connecting FileZilla to your Amazon EC2 instance enables you to transfer files easily between your local machine and your EC2 server. FileZilla, a widely-used FTP client, supports SFTP (SSH File Transfer Protocol), which provides a secure way to transfer files. This is particularly useful for developers or administrators who need to frequently upload or download files from their EC2 instance. Below is a step-by-step guide on how to set up a FileZilla client to connect with your EC2 instance:
- Open FileZilla: Launch FileZilla on your computer. If it's not installed, you can download it from the official website: https://filezilla-project.org/.
- Access Site Manager: In FileZilla, click on File > Site Manager to manage your connection settings.
- Create New Site: In the Site Manager, click on New Site and give it a recognizable name for your EC2 connection.
- Configure Connection Settings:
- Protocol: Select SFTP - SSH File Transfer Protocol.
- Host: Enter the Elastic IP or public instance IP of your EC2 instance.
- Logon Type: Choose 'Key file'.
- User: ec2-user.
- Key File: Add the path to your private key file (.pkk).
- Click on Ok (or Save)
- Connect: After configuring the settings, click Connect in the Site Manager (you can access the Site Manager directly by clicking the first button under the toolbar.) The first time you connect to your instance, you might receive a prompt to trust the host; accept it to proceed.
This setup allows you to securely manage files on your EC2 instance using FileZilla. Remember to keep your private key file secure and up to date. Efficient file management is crucial for maintaining the integrity and performance of your applications hosted on AWS.
Installing Apache / httpd
Installing Apache (also known as httpd) on your Amazon EC2 instance is a fundamental step for hosting websites or web applications. Apache is a widely-used web server software that offers robust and reliable performance. The following outlines the steps to install and configure Apache on an Amazon Linux EC2 instance. These steps include updating your instance, installing Apache, starting and enabling the service to run at boot, and configuring logging and directory settings for your project.
You can copy and paste the commands all at once in your PuTTY console window.
Update packages and install apache
# Update your instance package index
sudo yum update -y
# Install apache
sudo yum install httpd -y
# Start the Apache service
sudo systemctl start httpd
# Enable Apache to start on boot
sudo systemctl enable httpd
# (Optional) Check the status of the Apache service
# sudo systemctl status httpd
Create your project directory
By default the public directory, which is the directory where all files are publicly available, is in /var/www/html. So for security reasons we should not create our project directory in this folder. We could create a .htaccess file in this directory which serves files from our project directory, but that's for another tutorial.
# Create the project folder
sudo mkdir -p /var/www/**project**
# Set folder permissions to the current user and group (ec2-user)
sudo chown -R $USER:$USER /var/www/**project**
(Optional) Create a custom log directory
Change the location of the apache and php error logs.
# Create log folder
sudo mkdir -p /var/www/logs
# Set folder permissions
sudo chown -R $USER:$USER /var/www/logs
Change public folder permissions
Set /var/www/html (public folder) permissions so we can upload files there with the ec2-user using FileZilla.
# Change html folder ownership
sudo chown -R $USER:$USER /var/www/html
(optional) Configuring apache
Open the config file with vim (or change it for your favorite text editor.)
# Open the config file
sudo vim /etc/httpd/conf/httpd.conf
# How to use vim?
# Type "a" to access write mode
# Type ctrl+c to leave write mode (access view mode)
# Type :w (write) & enter to save changes (only in view mode)
# Type :q (quit) & enter to leave vim (only in view mode)
# Type / and then text to search to search the current document (only in view mode)
Change error log directories to the ones we created.
# Replace ErrorLog "logs/error_log" with:
ErrorLog "/var/www/logs/apache_error.log"
# Replace CustomLog "logs/access_log" combined with:
CustomLog "/var/www/logs/apache_access.log" combined
When using a .htaccess file in the public (html) folder, change AllowOverride to All in the www/html directory block.
Close vim (:q & enter) and make sure to test the changes:
sudo systemctl restart httpd
sudo systemctl status httpd
Now apache should work. When you go in your browser to your elastic ip (or the public ip of your EC2 instance,) you should see the apache test page. If you have an error page or an empty page then something went wrong.
Install PHP 8.0, PHP 8.1, PHP 8.2 or PHP 8.3
Installing a specific version of PHP, such as PHP 8.1, 8.2, or 8.3, on your Amazon EC2 instance can enhance the performance and security of your web applications. PHP is a popular server-side scripting language used in web development. As of this writing, PHP 8.3 is not available in the Amazon Linux extras repository, but might be available by the time you read this. Here’s how you can install PHP on an Amazon Linux EC2 instance and configure it, make sure to alter it to the version you need.
# List available packages in 'amazon-linux-extras' and filters for PHP-related packages
sudo amazon-linux-extras | grep php
# Enable the repository for PHP 8.2 in 'amazon-linux-extras'
sudo amazon-linux-extras enable php8.2
# Clear the metadata cache for 'yum' to ensure the package list is up-to-date
sudo yum clean metadata
# Install PHP along with common and essential extensions
sudo yum install php php-common php-pear -y
# Install a set of PHP extensions commonly used for web development
sudo yum install php-{cgi,curl,mbstring,gd,mysqlnd,gettext,json,xml,fpm,intl,zip}
# Test if PHP is correctly installed, this should show the right PHP version
php -version
PHP should be installed correctly now. If you want to change the php.ini settings, do the following:
# Open php.ini with vim
sudo vim /etc/php.ini
# Don't forget to restart the server
sudo systemctl restart httpd
Now you can test if PHP works correctly. Make a file index.php and put this in the file:
<?php
phpinfo();
?>
It is generally a bad idea to show your php info to the public, but for this tutorial we don't mind. Upload the file with FileZilla to /var/www/html and again visit in your browser your server IP. Now it should show the PHP info, everything works as it should.
Setting up https (SSL) for your website
Securing your website with HTTPS is crucial for safeguarding your users' data and enhancing their trust in your site. HTTPS, which stands for Hypertext Transfer Protocol Secure, encrypts data transmitted between a user's browser and your server, protecting it from interception or tampering. This is particularly important for sites handling sensitive information. The process involves obtaining an SSL (Secure Sockets Layer) certificate and configuring your web server to use it. Here’s a basic guide to setting up HTTPS for your website hosted on an Amazon EC2 instance:
# Install the SSL Apache module
sudo yum install mod_ssl
# Create the certificate files , paste your public and private keys
sudo vim /etc/ssl/certs/origin.crt
sudo vim /etc/ssl/certs/private.key
# Set file permissions
sudo chmod 600 /etc/ssl/certs/origin.crt
sudo chmod 600 /etc/ssl/certs/private.key
# Edit the configuration file
sudo vim /etc/httpd/conf.d/ssl.conf
# Change logging location if needed (find and change the line)
ErrorLog /var/www/logs/ssl_error.log
TransferLog /var/www/logs/ssl_access.log
# Make sure the next 3 lines have these values
SSLEngine on
SSLCertificateFile /etc/ssl/certs/origin.crt
SSLCertificateKeyFile /etc/ssl/certs/private.key
# Restart server
sudo systemctl restart httpd
# Test Apache status
sudo systemctl status httpd
By following these steps, you will have secured your website with HTTPS, providing a safer and more professional experience for your users. Remember, SSL certificates need to be renewed periodically, so keep track of the expiration date and renew it as necessary.