LAMP server tutorial with Apache, PHP 7, and MySQL

LAMP is short for Linux, Apache, MySQL, PHP. This tutorial shows how you can install an Apache web server on an Ubuntu 20.04.1 LTS server with PHP 7 (mod_php) and MySQL / MariaDB support and how to setup an SSL certificate with Let’s encrypt. Additionally, I will install PHPMyAdmin to make MySQL administration easier. A LAMP setup is a perfect basis for popular CMS systems like Joomla, WordPress or Drupal.

1. Install MariaDB 10

Run the following command to install MariaDB-server and client:

apt-cache search mariadb
sudo apt-get -y install mariadb-server-10.3 mariadb-client-10.3

Now we set a root password for MariaDB.

sudo mysql_secure_installation

You will be asked these questions:

Enter current password for root (enter for none): <-- press enter
Set root password? [Y/n] <-- y
New password: <-- Enter the new MariaDB root password here
Re-enter new password: <-- Repeat the password
Remove anonymous users? [Y/n] <-- y
Disallow root login remotely? [Y/n] <-- y
Reload privilege tables now? [Y/n] <-- y

Test the login to MariaDB with the “mysql command” and change global time zone

sudo mysql -u root -p

and enter the MariaDB root password that you’ve set above. The result should be similar to the screenshot below:

Set time zone

SET @@global.time_zone = '+07:00';

To leave the MariaDB shell, enter the command “quit” and press enter.

2. Install Apache Web Server

Apache 2 is available as an Ubuntu package, therefore we can install it like this:

sudo apt-get -y install apache2

Now direct your browser to http://192.168.1.100, and you should see the Apache2 default page (It works!):

The document root of the apache default vhost is /var/www/html on Ubuntu and the main configuration file is /etc/apache2/apache2.conf. The configuration system is fully documented in /usr/share/doc/apache2/README.Debian.gz.

3. Install PHP 7

We can install PHP 7 and the Apache PHP module as follows:

apt-cache search php7
sudo apt-get -y install php7.4 libapache2-mod-php7.4

Then restart Apache:

sudo systemctl restart apache2

4. Test PHP and get details about your PHP installation

The document root of the default web site is /var/www/html. We will now create a small PHP file (info.php) in that directory and call it in a browser. The file will display lots of useful details about our PHP installation, such as the installed PHP version.

sudo nano /var/www/html/info.php
<?php
phpinfo();
?>

Then change the owner of the info.php file to the www-data user and group.

sudo chown www-data:www-data /var/www/html/info.php

Now we call that file in a browser (e.g. http://192.168.1.100/info.php):

As you see, PHP 7.0 is working, and it’s working through the Apache 2.0 Handler, as shown in the Server API line. If you scroll further down, you will see all modules that are already enabled in PHP5. MySQL is not listed there which means we don’t have MySQL / MariaDB support in PHP yet.

5. Get MySQL / MariaDB support in PHP

To get MySQL support in PHP, we can install the php7.0-mysql package. It’s a good idea to install some other PHP modules as well as you might need them for your applications. You can search for available PHP modules like this:

apt-cache search php7

Pick the ones you need and install them like this:

sudo apt-get -y install php7.4-mysql php7.4-curl php7.4-gd php7.4-intl php7.4-imap php7.4-pspell php7.4-sqlite3 php7.4-tidy php7.4-xmlrpc php7.4-zip php7.4-xsl php7.4-mbstring php-pear php-imagick php-memcache gettext

Now restart Apache2:

sudo systemctl restart apache2

PHP 7 has now MySQL / MariaDB support as shown in phpinfo() above.

6. Install the Opcache + APCu PHP cache to speed up PHP

PHP 7 ships with a built-in opcode cacher for caching and optimizing PHP intermediate code, it has the name ‘opcache’ and is available in the package php7.0-opcache. It is strongly recommended to have an Opcache installed to speed up your PHP page. Besides opcache, I will install APCu which is a compatibility wrapper for opcache to provide the functions of the APC cache, an often used caching system in PHP 5.x versions and many CMS systems still use it.

Opcache and APCu can be installed as follows:

sudo apt-get -y install php7.4-opcache php-apcu

Don’t worry if it shows that Opcache is already installed.

Now restart Apache:

sudo systemctl restart apache2

Now reload http://192.168.1.100/info.php in your browser and scroll down to the modules section again. You should now find lots of new modules there:

Please don’t forget to delete the info.php file when you don’t need it anymore as it provides sensitive details of your server. Run the following command to delete the file.

sudo rm -f /var/www/html/info.php

7. Install phpMyAdmin

phpMyAdmin is a web interface through which you can manage your MySQL databases. It’s a good idea to install it:

sudo apt-get -y install phpmyadmin

IMPORTANT: The apt installer will ask you several questions now, one of them is to select the web server type. A common mistake is that the web server type is just highlighted but not selected. To select an item in a apt menu you have to press the space bar on the keyboard after you navigated to the item with tab or cursor keys. Just highlighting it is not ennough! When the first prompt appears, apache2 is highlighted, but not selected. If you do not hit “SPACE” to select Apache, the installer will not move the necessary files during installation. Hit “SPACE”, “TAB”, and then “ENTER” to select Apache.

You will see the following questions:

Web server to configure automatically: <-- Select the option: apache2
Configure database for phpmyadmin with dbconfig-common? <-- Yes
MySQL application password for phpmyadmin: <-- Press enter, apt will create a random password automatically.

7.1 Root access to PHPMyAdmin with MariaDB

The following step is required for MariaDB installations only, if you use MySQL 5.7, then skip this step.

MariaDB enables a plugin called “unix_socket” for the root user by default, this plugin prevents that the root user can log into PHPMyAdmin and that TCP connections to MySQL are working for the root user. To get a user with privileges to create other users and databases in PHPMyAdmin, I will create a new MySQL user with the name “admin” with the same privileges than the root user.

Login to the MySQL database as root user on the shell:

sudo mysql -u root

Create a new user with the name “admin” and password “howtoforge”. Replace the password “howtoforge” with a secure password in the commands below!

CREATE USER 'admin'@'localhost' IDENTIFIED BY 'howtoforge';
GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;
exit

Afterward, you can access phpMyAdmin under http://192.168.1.100/phpmyadmin/

If get error “The requested url /phpmyadmin/ was not found on this server”

sudo ln -s /usr/share/phpmyadmin /var/www/html/phpmyadmin

How to hide lacking phpmyadmin warnings? Goto /usr/share/phpmyadmin/libraries/config.default.php

#Edit 'ask' to 'never'
$cfg['SendErrorReports'] = 'never'

 

8. Manually Upgrading PHPMyAdmin

9. Protect with .htpasswd

We can further protect the phpMyAdmin login page with .htpasswd. This adds another line of defence against bots and attackers.

9.1 Configure Apache to Allow .htaccess Overrides

First, we need to enable the use of .htaccess file overrides by editing our Apache configuration file.

We will edit the linked file that has been placed in our Apache configuration directory:

sudo nano /etc/apache2/conf-available/phpmyadmin.conf
#sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-available/phpmyadmin.conf
#sudo a2enconf phpmyadmin
#sudo /etc/init.d/apache2 reload

We need to add an AllowOverride All directive within the <Directory /usr/share/phpmyadmin> section of the configuration file, like this:

<Directory /usr/share/phpmyadmin>
    Options FollowSymLinks
    DirectoryIndex index.php
    AllowOverride All
    . . .

When you have added this line, save and close the file.

To implement the changes you made, restart Apache:

sudo systemctl restart apache2

9.2 Create an .htaccess File

Now that we have enabled .htaccess use for our application, we need to create one to actually implement some security.

In order for this to be successful, the file must be created within the application directory. We can create the necessary file and open it in our text editor with root privileges by typing:

sudo nano /usr/share/phpmyadmin/.htaccess

Within this file, we need to enter the following information:/usr/share/phpmyadmin/.htaccess

AuthType Basic
AuthName "Restricted Files"
AuthUserFile /etc/phpmyadmin/.htpassword
Require valid-user

Let’s go over what each of these lines mean:

  • AuthType Basic: This line specifies the authentication type that we are implementing. This type will implement password authentication using a password file.
  • AuthName: This sets the message for the authentication dialog box. You should keep this generic so that unauthorized users won’t gain any information about what is being protected.
  • AuthUserFile: This sets the location of the password file that will be used for authentication. This should be outside of the directories that are being served. We will create this file shortly.
  • Require valid-user: This specifies that only authenticated users should be given access to this resource. This is what actually stops unauthorized users from entering.

9.3 Create the .htpasswd file for Authentication

The location that we selected for our password file was “/etc/phpmyadmin/.htpasswd”. We can now create this file and pass it an initial user with the htpasswd utility:

sudo htpasswd -c /etc/phpmyadmin/.htpassword username

You will be prompted to select and confirm a password for the user you are creating. Afterwards, the file is created with the hashed password that you entered.

If you want to enter an additional user, you need to do so without the -c flag, like this:

sudo htpasswd /etc/phpmyadmin/.htpasswd additionaluser

Now, when you access your phpMyAdmin subdirectory, you will be prompted for the additional account name and password that you just configured:

https://domain_name_or_IP/phpmyadmin
phpMyAdmin apache password

After entering the Apache authentication, you’ll be taken to the regular phpMyAdmin authentication page to enter your other credentials. This will add an additional layer of security since phpMyAdmin has suffered from vulnerabilities in the past.

10. Enable the SSL website in apache

SSL/ TLS is a security layer to encrypt the connection between the web browser and your server. Most web browsers start to show sites as insecure today when the connection between the server and the web browser is not encrypted with SSL. In this chapter, I will show you how to secure your website with SSL.

Execute the following commands on your server to enable SSL (https://) support. Run:

a2enmod ssl
a2ensite default-ssl

which enables the SSL module and adds a symlink in the /etc/apache2/sites-enabled folder to the file /etc/apache2/sites-available/default-ssl.conf to include it into the active apache configuration. Then restart apache to enable the new configuration:

systemctl restart apache2

Now test the SSL connection by opening https://192.168.1.100 in a web browser.

You will receive an SSL warning as the SSL certificate of the server is a “self-signed” SSL certificate, this means that the browser does not trust this certificate by default and you have to accept the security warning first. After accepting the warning, you will see the apache default page.

The closed “Green Lock” in front of the URL in the browser shows that the connection is encrypted.

There are two ways to get rid of the SSL warning, either replace the self-signed SSL certificate /etc/ssl/certs/ssl-cert-snakeoil.pem with an officially signed SSL certificate that you buy from an SSL Authority or you get a free SSL certificate from Let’s encrypt, which I will describe in chapter 8.

11. Get a free SSL Certificate from Let’s Encrypt

The first step to secure the website with a Let’s Encrypt SSL Certificate is to install the python-letsencrypt-apache package. Run the following command:

sudo apt-get -y install python3-certbot-apache

In the next step, we will request an SSL cert from Let’s Encrypt, during this process, the Let’s Encrypt server tries to connect to your server trough the domain name that you provide to the letsencrypt command. It is important that this domain name points to your server in DNS already so that the website is reachable by its domain name on port 80 (http) already. If the website is not reachable from the internet, then the creation of the Let’s Encrypt SSL certificate will fail.

Before we can start to create the SSL cert, set the domain name in the vhost configuration file. Open the default vhost file with an editor:

nano /etc/apache2/sites-available/000-default.conf

and add the content:

<VirtualHost *:80>
	ServerName xuan-nguyen.vn 
	ServerAlias www.xuan-nguyen.vn
	ServerAdmin webmaster@localhost
	DocumentRoot /media/ssd256gb/wordpress/cosmetics.xuan-nguyen.vn
		<Directory /media/ssd256gb/wordpress/cosmetic.xuan-nguyen.vn>
                        Options Indexes FollowSymLinks
                        AllowOverride All
                        Require all granted
                </Directory>

	ErrorLog ${APACHE_LOG_DIR}/error.log
	CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<VirtualHost *:80>
  ServerName cosmetic.xuan-nguyen.vn 
	ServerAlias www.cosmetic.xuan-nguyen.vn
	ServerAdmin webmaster@localhost
	DocumentRoot /media/ssd256gb/wordpress/cosmetic.xuan-nguyen.vn
		<Directory /media/ssd256gb/wordpress/cosmetic.xuan-nguyen.vn>
                        Options Indexes FollowSymLinks
                        AllowOverride All
                        Require all granted
                </Directory>

	ErrorLog ${APACHE_LOG_DIR}/error.log
	CustomLog ${APACHE_LOG_DIR}/access.log combined
 </VirtualHost>


<VirtualHost *:80>
  ServerName blog.xuan-nguyen.vn 
	ServerAlias www.blog.xuan-nguyen.vn
	ServerAdmin webmaster@localhost
	DocumentRoot /media/ssd256gb/wordpress/blog.xuan-nguyen.vn
		<Directory /media/ssd256gb/wordpress/blog.xuan-nguyen.vn>
                        Options Indexes FollowSymLinks
                        AllowOverride All
                        Require all granted
                </Directory>

	ErrorLog ${APACHE_LOG_DIR}/error.log
	CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<VirtualHost *:80>
  ServerName apps.xuan-nguyen.vn
	ServerAdmin webmaster@localhost
	DocumentRoot /var/www/html
 
  	Alias /daihuudsf /media/ssd256gb/bindfs/nextcloud/linh3t/nodejs/daihuudsf/images
		<Directory /media/ssd256gb/bindfs/nextcloud/linh3t/nodejs/daihuudsf/images>
        		Options Indexes FollowSymLinks
        		AllowOverride All
        		Require all granted
		</Directory>

	Alias /dqpclient /media/ssd256gb/bindfs/nextcloud/linh3t/nodejs/dqpclient/images
        	<Directory /media/ssd256gb/bindfs/nextcloud/linh3t/nodejs/dqpclient/images>
                	Options Indexes FollowSymLinks
                	AllowOverride All
                	Require all granted
        	</Directory>

	ErrorLog ${APACHE_LOG_DIR}/error.log
	CustomLog ${APACHE_LOG_DIR}/access.log combined
 </VirtualHost>


<VirtualHost *:80>
  ServerName dqpapps.tk
	ServerAlias www.dqpapps.tk
	ServerAdmin webmaster@localhost
	DocumentRoot /var/www/html
 
  	Alias /daihuudsf /media/ssd256gb/bindfs/nextcloud/linh3t/nodejs/daihuudsf/images
		<Directory /media/ssd256gb/bindfs/nextcloud/linh3t/nodejs/daihuudsf/images>
        		Options Indexes FollowSymLinks
        		AllowOverride All
        		Require all granted
		</Directory>

	Alias /dqpclient /media/ssd256gb/bindfs/nextcloud/linh3t/nodejs/dqpclient/images
        	<Directory /media/ssd256gb/bindfs/nextcloud/linh3t/nodejs/dqpclient/images>
                	Options Indexes FollowSymLinks
                	AllowOverride All
                	Require all granted
        	</Directory>

	ErrorLog ${APACHE_LOG_DIR}/error.log
	CustomLog ${APACHE_LOG_DIR}/access.log combined
 </VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

Then create the SSL Certificate with this command:

sudo letsencrypt --apache --redirect -m linh3t@gmail.com -d xuan-nguyen.vn -d www.xuan-nguyen.vn -d cosmetic.xuan-nguyen.vn -d blog.xuan-nguyen.vn

Make some change for new domain name

sudo service apache2 restart

When you access the website now with a browser, you will get redirected automatically to SSL and the green lock in front of the URL bar in the browser shows that we are using a trusted SSL certificate now.

11.1 Let’s encrypt Auto Renewal

Let’s Encrypt SSL certificates are valid for a short period of 80 days only. Therefore we will setup a cronjob now to auto-renew the SSL certificate when necessary. The command is ‘letsencrypt renew’.

Setup a cronjob for Let’s Encrypt auto renewal. Run:

sudo crontab -e # add cronjob for root

to open the root crontab in an editor. Insert the following line at the end of the file:

0 3 * * 0 /usr/bin/letsencrypt --redirect -m linh3t@gmail.com --agree-tos --renew-by-default -d xuan-nguyen.vn -d www.xuan-nguyen.vn -d blog.xuan-nguyen.vn -d cosmetic.xuan-nguyen.vn >/dev/null 2>&1

save the file, this will activate the cronjob. This cronjob will call the Let’s Encrypt renew command every sunday at 3:0:0 am. The command will renew the SSL cert only when necessary (30 days before it expires), there is no problem to run it every week.

12 Virtual machine image download of this tutorial

This tutorial is available as ready to use virtual machine image in ovf/ova format that is compatible with VMWare and Virtualbox. The virtual machine image uses the following login details:

SSH / Shell Login

Username: administrator
Password: howtoforge

This user has sudo rights.

MySQL Login

Username: root
Password: howtoforge

The IP of the VM is 192.168.1.100, it can be changed in the file /etc/network/interfaces. Please change all the above passwords to secure the virtual machine.

Leave a Reply

Your email address will not be published. Required fields are marked *