Current Location: Home> Latest Articles> Comprehensive Guide to Configuring PHP and Apache on Linux Servers

Comprehensive Guide to Configuring PHP and Apache on Linux Servers

gitbox 2025-07-31

Guide to Configuring PHP and Apache on Linux

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.

Environment Preparation

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

Configure Apache to Support 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

Test the PHP Environment

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.

Configure Apache Virtual Hosts

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>

Set Permissions and Restart Apache

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

Conclusion

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.