Empowering you with the knowledge to master Linux web hosting, DevOps and Cloud

 Linux Web Hosting, DevOps, and Cloud Solutions

Tag: mysql

Step-by-Step Tutorial: Setting up Apache, MySQL, PHP (LAMP Stack) on Ubuntu 22.04 for Beginners

What is a LAMP Stack?

LAMP stack is a popular combination of open-source software that is used to run dynamic websites and web applications. The acronym LAMP stands for Linux (operating system), Apache (web server), MySQL (database management system), and PHP (scripting language).

Linux provides the foundation for the LAMP stack, serving as the operating system on which the other software components are installed. Apache is the web server that handles HTTP requests and serves web pages to users. MySQL is a powerful database management system that is used to store and manage website data. PHP is a popular scripting language used to create dynamic web content, such as interactive forms and web applications.

Together, these software components create a powerful platform for building and deploying web applications. The LAMP stack is highly customizable and widely used, making it an excellent choice for developers and system administrators alike.

Prerequisites

1. Ubuntu server: You will need an Ubuntu server to install the LAMP stack. You can use a Virtual/CLoud server or a physical server as per your requirement.

2. SSH access: You will need SSH access to your Ubuntu server to be able to install the LAMP stack. SSH (Secure Shell) is a secure network protocol that allows you to access and manage your server remotely.

3. Non-root user with sudo privileges: It is recommended that you use a non-root user with sudo privileges to install and configure the LAMP stack. This is because running as root can pose a security risk and may lead to unintended consequences if something goes wrong. You can also run the commands as root user.

4. Basic familiarity with Linux command line: A basic understanding of how to use the Linux command line interface (CLI) to run commands and navigate your Ubuntu server is recommended, not mandatory.

Installing a LAMP Stack on Ubuntu
In this section, the process of installing a LAMP Stack on Ubuntu 22.04 LTS is outlined. These instructions can be applied to Ubuntu 20.04 LTS as well.

A LAMP stack is a popular combination of open-source software used to run dynamic websites or web applications. LAMP stands for Linux (operating system), Apache (web server), MySQL (database management system), and PHP (scripting language). In this guide, we will walk you through the steps involved in installing and configuring a LAMP stack on an Ubuntu server.

Step 1: Update Your Ubuntu Server
Before we begin installing LAMP stack components, let’s update the server’s software packages by running the following command:

sudo apt update && sudo apt upgrade

Step 2: Install Apache
Apache is the most widely used web server software. To install it, run the following command:

sudo apt install apache2

Once the installation is complete, you can check the status of Apache by running the following command:

sudo systemctl status apache2
This will display Apache’s status as either active or inactive.

Step 3: Install MySQL
MySQL is a popular open-source database management system. To install it, run the following command:

sudo apt install mysql-server
Once the installation is complete, you can check the status of MySQL by running the following command:

sudo systemctl status mysql
This will display MySQL’s status as either active or inactive.

Step 4: Install PHP
PHP is a popular server-side scripting language used to create dynamic web content. To install it, run the following command:

sudo apt install php libapache2-mod-php php-mysql

There are several additional PHP modules recommended for a CMS like WordPress. You can install them by running the command below:
sudo apt-get install php-curl php-gd php-xml php-mbstring php-imagick php-zip php-xmlrpc
After installing these modules, you will need to restart your Apache server for the changes to take effect. You can do this by running the following command:

sudo systemctl restart apache2

Setting up firewall rules to allow access to Apache web server

UFW is the default firewall with Ubuntu systems, providing a simple command-line interface to configure iptables, the software-based firewall used in most Linux distributions. UFW provides various application profiles that can be utilized to manage traffic to and from different services. To view a list of all the available UFW application profiles, you can run the command:

sudo ufw app list

Output
Available applications:
Apache
Apache Full
Apache Secure
OpenSSH

These application profiles have different configurations for opening specific ports on the firewall. For instance:

Apache: Allows traffic on port 80, which is used for normal, unencrypted web traffic.
Apache Full: Allows traffic on both port 80 and port 443, which is used for TLS/SSL encrypted traffic.
Apache Secure: Allows traffic only on port 443 for TLS/SSL encrypted traffic.

To allow traffic on both port 80 and port 443(SSL), you can use the Apache Full profile by running the following command:

sudo ufw allow in "Apache Full"

You can verify that the change has been made by running the command:
sudo ufw status

Output

Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere                                
Apache Full                ALLOW       Anywhere                  
OpenSSH (v6)               ALLOW       Anywhere (v6)                    
Apache Full(v6)            ALLOW       Anywhere (v6)   

To test if the ports are open and Apache web server is accessible, you can try visiting your server’s public IP address in a web browser using the URL http://your_server_ip. If successful, you should see the default Apache web page.

If you can view this page, your web server is correctly installed and accessible through your firewall.

Configuring the MySQL Database server
Upon installation of MySQL, it is immediately available for use. However, in order to utilize it for web applications such as WordPress and improve the security of said applications, it is imperative to generate a database user and database. To complete the configuration process for MySQL, please adhere to the following steps.

To configure MySQL and improve application security, follow these steps:

1. Log in to the MySQL shell as the root user:

sudo mysql -u root

2. Using the MySQL shell, you can create the wpdatabase database and generate a new user account for accessing the web application. Instead of using the placeholders “dbuser” and “password” in the CREATE USER query, you should provide a real username and password. Furthermore, you should grant complete permissions to the user. After each line, MySQL should respond with “Query OK.”

CREATE DATABASE wpdatabase ;
CREATE USER 'dbuser' IDENTIFIED BY 'password';
GRANT ALL ON wpdatabase .* TO 'dbuser';

Exit the SQL shell:
quit

3. Set a password for root’@’localhost:

sudo mysql
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password by 'password';

Exit the SQL shell:
quit

Note: Replace “password” with a strong password.
4. Use the mysql_secure_installation tool to increase database security:

sudo mysql_secure_installation

When prompted to change the root password, leave it unchanged. Answer Y for the following questions:

Remove anonymous users?
Disallow root login remotely?
Remove test database and access to it?
Reload privilege tables now?

To log in to the MySQL shell as root after this change, use “sudo mysql -u root” and type “quit” exit the SQL Shell.

It’s worth noting that when connecting as the root user, there’s no need to enter a password, despite having defined one during the mysql_secure_installation script. This is due to the default authentication method for the administrative MySQL user being unix_socket rather than password. Although it may appear to be a security issue, it actually strengthens the security of the database server by only allowing system users with sudo privileges to log in as the root MySQL user from the console or through an application with the same privileges. As a result, you won’t be able to use the administrative database root user to connect from your PHP application. However, setting a password for the root MySQL account acts as a precautionary measure in case the default authentication method is changed from unix_socket to password.

Creating a Virtual Host for your Website

In order to host multiple domains from a single server, Apache web server provides the capability to create virtual hosts. These virtual hosts are beneficial as they allow you to encapsulate configuration details for each domain. In this tutorial, we will walk you through setting up a domain named “example.com”. However, it is important to keep in mind that you should replace “example.com” with your own domain name.

By default, Ubuntu 22.04’s Apache web server has a single virtual host that is enabled and configured to serve documents from the /var/www/html directory. While this is a workable solution for a single site, it becomes cumbersome when hosting multiple sites. Therefore, instead of modifying /var/www/html, we will create a directory structure within the /var/www directory specifically for the example.com site. In doing so, we will leave /var/www/html in place as the default directory to be served if a client request does not match any other sites.

1. First, create a new directory for the “example.com” website files:

sudo mkdir /var/www/example.com

2. Assign the ownership of the directory to the web server user (www-data):

sudo chown -R www-data:www-data /var/www/example.com

3. Create a new virtual host configuration file for “example.com” using the nano text editor:

sudo nano /etc/apache2/sites-available/example.com.conf

4. Add the following configuration to the file, replacing “example.com” with your own domain name:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com

    <Directory /var/www/example.com>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
    CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
</VirtualHost>

This configuration specifies that the “example.com” domain should use the files located in the /var/www/example.com directory as its document root.

5. Disable the default Apache site configuration to avoid conflicts:

sudo a2dissite 000-default.conf

6. Enable the “example.com” site configuration:
sudo a2ensite example.com.conf

7. Restart Apache to apply the changes:
sudo systemctl restart apache2

8. Create a test “hello world” HTML file:
sudo nano /var/www/example.com/index.html

Add the following HTML code to the file:

<!DOCTYPE html>
<html>
<head>
    <title>Hello World</title>
</head>
<body>
    <h1>Hello World!</h1>
</body>
</html>

9. Save and close the file.

10. Finally, configure your DNS records to point the “example.com” domain to your server’s IP address. Once the DNS records are updated, you can access the website by visiting “http://example.com” in your web browser.

Testing the LAMP Stack Installation on Your Ubuntu Server
To ensure that the LAMP stack configuration is fully functional, it’s necessary to conduct tests on Apache, PHP, and MySQL components. Verifying the Apache operational status and virtual host configuration was done earlier. Now, it’s important to test the interaction between the web server and PHP and MySQL components.

The easiest way to verify the configuration of the Ubuntu LAMP stack is by using a short test script. The PHP code does not need to be lengthy or complex; however, it must establish a connection to MySQL. The test script should be placed within the DirectoryRoot directory.

To validate the database, use PHP to invoke the mysqli_connect function. Use the username and password created in the “Configuring the MySQL Database server” section. If the attempt is successful, the mysqli_connect function returns a Connection object. The script should indicate whether the connection succeeded or failed and provide more information about any errors.

To verify the installation, follow these steps:

1. Create a new file called “phptest.php” in the /var/www/example.com directory.

<html>
<head>
    <title>PHP MySQL Test</title>
</head>
    <body>
    <?php echo '<p>Welcome to the Site!</p>';

    // When running this script on a local database, the servername must be 'localhost'. Use the name and password of the web user account created earlier. Do not use the root password.
    $servername = "localhost";
    $username = "dbuser";
    $password = "password";

    // Create MySQL connection
    $conn = mysqli_connect($servername, $username, $password);

    // If the conn variable is empty, the connection has failed. The output for the failure case includes the error message
    if (!$conn) {
        die('<p>Connection failed: </p>' . mysqli_connect_error());
    }
    echo '<p>Connected successfully</p>';
    ?>
</body>
</html>

2. To test the script, open a web browser and type the domain name followed by “/phptest.php” in the address bar. For example, if your domain name is “example.com”, you would enter “example.com/phptest.php” in the address bar. Make sure to substitute the actual name of the domain for “example.com” in the example provided.

http://example.com/phptest.php

3. Upon successful execution of the script, the web page should display without any errors. The page should contain the text “Welcome to the Site!” and “Connected successfully.” However, if you encounter the “Connection Failed” error message, review the SQL error information to troubleshoot the issue.

Bonus: Install phpMyAdmin
phpMyAdmin is a web-based application used to manage MySQL databases. To install it, run the following command:

sudo apt install phpmyadmin
During the installation process, you will be prompted to choose the web server that should be automatically configured to run phpMyAdmin. Select Apache and press Enter.

You will also be prompted to enter a password for phpMyAdmin’s administrative account. Enter a secure password and press Enter.

Once the installation is complete, you can access phpMyAdmin by navigating to http://your_server_IP_address/phpmyadmin in your web browser.

Congratulations! You have successfully installed and configured a LAMP stack on your Ubuntu server.

Summary
This guide walks through the process of setting up a LAMP Stack, a combination of the Linux operating system, Apache web server, MySQL RDBMS, and PHP programming language, to serve PHP websites and applications. The individual components are free and open source, designed to work together, and easy to install and use. Following the steps provided, you can install the LAMP Stack on Ubuntu 22.04 LTS using apt, configure the Apache web server, create a virtual host for the domain, and integrate the MySQL web server by creating a new account to represent the web user. Additional PHP packages are required for Apache, PHP, and the database to communicate. A short PHP test script can be used to test the new installation by connecting to the database.

Password protect phpMyAdmin through CentOS Web panel(CWP)

phpMyAdmin is installed with CentOS Web Panel. By default, it is not protected and there is only MySQL user authentication. This can put your server vulnerable. So it is recommended to add additional layer protection.

phpMyAdmin is available through the following url in a CWP based server.

http:/hostname/phpmyadmin
http:/hostname:2030/pma

CWP panel runs its core services through its own version of Nginx. So normal htaccess based password protection will not work.

Create the Password File

You can do this by using the OpenSSL utilities that may already be available on your server. Alternatively, you can use the purpose-made htpasswd utility included in the apache2-utils package(Debian/ubuntu) or httpd-tools(Redhat/Centos).

Using OpenSSL Utilities

We will create a hidden file called .pma_pass /usr/local/cwpsrv/var/services/ folder. You can use any username. I am using dbadmin here as an example

sudo sh -c "echo -n 'dbadmin:' >> /usr/local/cwpsrv/var/services/.pma_pass"

Next, add an encrypted password entry for the username by typing:

sudo sh -c "openssl passwd -apr1 >> /usr/local/cwpsrv/var/services/.pma_pass"

Using Apache Utilities

This tool is already installed and available on all CWP servers.

/usr/local/apache/bin/htpasswd -c /usr/local/cwpsrv/var/services/.pma_pass dbadmin

Configure Nginx Password Authentication

We will need to configure Nginx to read this file before serving our protected content.
CWP Service Nginx configuration file: /usr/local/cwpsrv/conf/cwp_services.conf

Open the above file add the following to the location block of phpMyAdmin.

auth_basic “Admin Login”;
auth_basic_user_file /usr/local/cwpsrv/var/services/pma_pass;

So the full block should look like this now.

location /pma {
    root /usr/local/cwpsrv/var/services;
    index  index.html index.htm index.php;
    ModSecurityEnabled off;
    ModSecurityConfig /usr/local/cwpsrv/conf/security/conf/pma_rules.conf;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_read_timeout 600;
        fastcgi_pass    unix:/usr/local/cwp/php71/var/sockets/cwpsvc.sock;
        fastcgi_index   index.php;
        fastcgi_param   SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_param   SCRIPT_NAME   $fastcgi_script_name;
        include                 fastcgi_params;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        access_log    off;
        log_not_found    off;
        expires 1M;
    }

       auth_basic "Admin Login";
       auth_basic_user_file /usr/local/cwpsrv/var/services/.pma_pass;
}

Restart CWP nginx service by below commands

systemctl restart cwpsrv.service

Confirm the Password Authentication

To confirm that your content is protected, try to access your restricted content in a web browser. You should be presented with a username and password prompt

Problems logging into Plesk because of IP restrictions

Hello,

If you receive following error while logging to the Plesk panel, that means there is a IP based restriction to access Plesk admin panel and your current IP is not allowed to access.

“Unable to log into Plesk: Access for administrator from address xx.xx.xx.xx is restricted in accordance with IP Access restriction policy currently applied”

Cause
Plesk IP access policy was configured in such a way so that Plesk could not be accessed from the certain IP.

Resolution

Method 1. To enable Plesk access, you need to log into the Plesk from another IP and change the IP access policy:

Tools and Settings > Restrict Administrative Access
Add your IP to the whitelist

Method 2. Updating the database directly

If you cannot login to the panel, then you can connect to the server using SSH and correct this through database queries. Plesk database records regarding the access policy need to be corrected.

To retrieve the current policy and the restricted/allowed IPs, the following commands can be used:

Linux

#MYSQL_PWD=`cat /etc/psa/.psa.shadow` mysql -u admin psa
    mysql> select * from cp_access;
    mysql> select * from misc where param='access_policy';

Windows

"%plesk_bin%\dbclient" --direct-sql --sql="select * from cp_access"
    "%plesk_bin%\dbclient" --direct-sql --sql="select * from misc where param='access_policy'";

If you wish to clear the access policy settings, remove all records from “cp_access” and set the policy to “allow”:

Linux

# MYSQL_PWD=`cat /etc/psa/.psa.shadow` mysql -u admin psa
    mysql> delete from cp_access;
    mysql> update misc set val="allow" where param='access_policy';

Windows

"%plesk_bin%\dbclient" --direct-sql --sql="delete from cp_access";
    "%plesk_bin%\dbclient" --direct-sql --sql="update misc set val='allow' where param='access_policy'";

To whitelist the IP manually

bash# mysql -uadmin -p`cat /etc/psa/.psa.shadow ` psa

insert into cp_access values ("", "deny", "x.x.x.", "255.255.255.255"); //change the IP address to your public IP.

Then you should be able to connect to the Plesk control panel from the new IP address.

Powered by WordPress & Theme by Anders Norén