In modern web development, Linux is a stable and efficient server operating system, and its combination with PHP and Apache has become a popular choice for many developers. This article walks you through the process of properly installing and configuring PHP and Apache, starting from environment preparation to help you build and optimize your web server setup.
First, ensure your Linux system is updated and has the latest versions of Apache and PHP installed. You can install them with the following commands:
sudo apt update
sudo apt install apache2 php libapache2-mod-php
After installation, configure Apache to handle PHP files. Edit the main Apache configuration file:
sudo nano /etc/apache2/apache2.conf
Make sure the configuration includes the following line so that Apache processes PHP scripts correctly:
AddType application/x-httpd-php .php
To verify that PHP is configured properly, create a simple test file by running:
sudo nano /var/www/html/info.php
Insert the following code:
<?php
phpinfo();
?>
Save and then open http://your_server_ip/info.php in your browser. You should see a detailed PHP information page.
To better manage multiple websites, set up virtual hosts for each site. Create a virtual host configuration file:
sudo nano /etc/apache2/sites-available/mywebsite.conf
Add the following configuration (replace mywebsite with your website’s name):
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/mywebsite
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Make sure the website directory has the correct permissions by running:
sudo chown -R www-data:www-data /var/www/mywebsite
Enable the new site configuration and restart Apache:
sudo a2ensite mywebsite.conf
sudo systemctl restart apache2
Following these steps, you have successfully set up PHP and Apache on your Linux server. Proper configuration improves server performance and lays a solid foundation for future development and deployment. This guide aims to help you achieve a smooth Linux environment setup.