How to Install and Configure an SSL Certificate | How To Create a Self-Signed SSL Certificate for Apache in Ubuntu 24.04

Image : How To Create a Self-Signed SSL Certificate

Introduction

I am a PHP developer. I use Linux, Apache, MySQL, and PHP to further that goal.

This video/article will show how to create a self signed SSL on a test virtual machine running on a private IP with a non-routable domain name with the Top Level Domain (TLD) of .internal.

I only use self signed SSL’s for my test servers that I have created. For production I use Let’s Encrypt.

The steps below will show how to create a self signed SSL certificate for a  virtual host. Using these instruction each virtual server will have it’s own certificate.

I include the instructions for configuring the secured Apache configuration including PHP-FPM. If you are not using PHP-FPM you can remove that code from the Apache secured configuration as provided.

Prerequisites

    • Access to a web server via SSH.
    • A user capable of becomming sudo.

Overview

You’ll:

1. Create a self-signed certificate for one <-domain.tld-> , in my case that will be ‘lamp.internal’.  The Top Level Domain (TLD) of .internal is not publicly routable.
2. Configure one virtual host for one domain using the cert.
3. Enable the virtual host in Apache.

Step 1. Create Self-Signed Certificates

For each domain, <-domain.tld-> (use the domain name and TLD that you desire), run:

    • sudo mkdir -p /etc/ssl/internal/<-domain.tld->
    • sudo openssl req -x509 -nodes -days 825 -newkey rsa:2048 \
      -keyout /etc/ssl/internal/<-domain.tld->/<-domain.tld->.key \
      -out /etc/ssl/internal/<-domain.tld->/<-domain.tld->.crt \
      -subj “/C=<-YourCountryCode->/ST=<-YourState->/L=<-YourCity->/O=<-YourCompany->/OU=<-YourDepartment->/CN=<-domain.tld->”

Replace

    • <-domain.tld-> with your domain.
    • <-YourCountryCode-> with your company code.
    • <-YourState-> with your state.
    • <-YourCity-> with your city.
    • <-YourCompany-> with your company.
    • <-YourDepartment-> with your department.

Step 2. Create Apache Virtual Host Config

Create a file like /etc/apache2/sites-available/<-domain.tld-ssl->.conf with the following contents.

    • sudo vi /etc/apache2/sites-available/<-domain.tld-ssl->.conf

<VirtualHost *:443>
    ServerName <-domain.tld->
    ServerAlias www.<-domain.tld-> # if you are configuring your virtual host to redirect to <-www.domain.tld-> you will need this directive.
    DocumentRoot /var/www/<-domain.tld->/public_html

    SSLEngine on
    SSLCertificateFile /etc/ssl/internal/<-domain.tld->/<-domain.tld->.crt
    SSLCertificateKeyFile /etc/ssl/internal/<-domain.tld->/<-domain.tld->.key

    # mod_rewrite
    # .htaccess has the other needed mod_rewrite code
    <Directory /var/www/<-domain.tld->/public_html/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    # Start PHP-FPM
    # This is the PHP-FPM code. If you are not running PHP-FPM you can comment out or remove.
    # Adjust PHP socket version if needed.
    <FilesMatch \.php$>
        SetHandler "proxy:unix:/var/run/php/php8.3-fpm.<-php-fpm-user->.sock|fcgi://localhost/"
    </FilesMatch>
    # End PHP-FPM

    ErrorLog ${APACHE_LOG_DIR}/<-domain.tld->.error.log
    CustomLog ${APACHE_LOG_DIR}/<-domain.tld->.access.log combined

</VirtualHost>

Step 3 Enable SSL and Site

    • sudo a2enmod ssl
    • sudo a2ensite <-domain.tld-ssl->.conf.
    • sudo systemctl reload apache2

Step 4. Add Domain to /etc/hosts file

    • sudo vi /etc/hosts
    • hit the i key to put vi in insert mode
    • add a line return
    • Enter the IP of the server, then a tab, then <-domain.tld->
    • Enter the IP of the server, then a tab, then www.<-domain.tld->
    • Press the escape key to exit insert mode
    • Press the colon key
    • Press the q key followed by the w key, followed by the enter key
    • These steps will configure the local virtual server.
    • In my case the Virtual host resides on VirtualBox that is installed on a Windows 10 laptop so the Windows host file needs to be updated as well.
    • To update the Windows host file:
      • Launch as notepad as administrator by right mouse clicking on notepad and selecting “Run as administrator”.
      • From the top menu click on Open.
      • Travers to Windows->System32->drivers->etc.
      • In the lower right of the dialog  box set the file exnstention to “All Files (*.*).
      • Click on the file hosts.
      • Scroll to the bottom and press return to obtain a new line.
      • Press the tabb key, enter the domain followed by another tab then enter the domain name.
      • From the main file click on File, Select save and exit the diaolg pager.
    •  If you are on a Linux Desktop then you will need to update that Linux box’s /etc/host file:
      • At the command line enter “sudo vi /etc/hosts
      • hit the i key to put vi in insert mode
      • add a line return
      • Enter the IP of the server, then a tab, then <-domain.tld->
      • Enter the IP of the server, then a tab, then www.<-domain.tld->
      • Press the escape key to exit insert mode
      • Press the colon key
      • Press the q key followed by the w key, followed by the enter key

Step 5. Verify the Apache Configuration

    • sudo apache2ctl configtest
    • Should Return : Syntax OK

Step 6. Verify SSL Certificate:

Use openssl to test:

echo -e "GET / HTTP/1.1\r\nHost: <-domain.tld->\r\nConnection: close\r\n\r\n" | openssl s_client -connect <-domain.tld->:443 -servername <-domain.tld-> -quiet

Look for:

    • Verify return code: 0 (ok)
    • verify error:num=18:self-signed certificate : this is normal.
    • Run : sudo apache2ctl configtest – which will return “Syntax OK”

Step 7. Check with a Browser:

    • Visit https://<-domain.tld-> to verify. (ensure it is https)
    • Since this is self signed, there will be an SSL warning.

Since I am doing this for PHP development and for testing, all my websites are on a local web server that is on a private domain. To resolve my non-routable domain names, I use the Windows and Linux hosts files as a simple domain name system (DNS). If I am using the private IP range of 192.168.1.001 to 192.168.1.253 and I configure my server to use the IP 192.168.1.55 I would add “192.168.1.55<tab><-domain.tld->” to the Windows and Linux hosts files.

When accessing this private server that is configured with a self-signed cert, your browser will show a warning — you can proceed manually.

To create more self-signed certificates for other virtual hosting accounts just repeat these instruction.

Conclusion

That’s it. With this setup, I can easily create self-signed SSL certificates for any of my test environments running on private, non-routable Top Level Domain (TLD). Each virtual host gets its own certificate, and the Apache configuration can be reused and tweaked as needed — especially if you’re using PHP-FPM. This is how I like to keep my development environments secure and consistent without relying on external certificate authorities. For production, I always use Let’s Encrypt — but for local testing, this works just fine.

How to Reset the MySQL Root Password on Ubuntu

Image : How to Reset the MySQL Root Password on Ubuntu

To reset the MySQL root password on Ubuntu 24.04, follow these steps. This works for MySQL 8.x as installed via the default Ubuntu repositories.

1) Stop MySQL service

    • sudo systemctl stop mysql

2) Create the mysqld directory

We need to create the mysql directory because systemctl removes the mysqld directry and it’s contents when MySQL is stopped. When we start MySQL in safe mode the mysql directory is not automatically created as it would be if MySQL was started using systemctl.

    • sudo mkdir -p /var/run/mysqld
    • sudo chown mysql:mysql /var/run/mysqld

3) Start MySQL in safe mode (skip authentication)

This starts MySQL without asking for a password and prevents remote access during this mode.

    • sudo mysqld_safe --skip-grant-tables --skip-networking &

3) Log in to MySQL without a password

    • mysql -u root

4) Change the root password

Inside the MySQL prompt, run:

    • FLUSH PRIVILEGES;
    • ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'newpassword';
    • FLUSH PRIVILEGES;

Replace ‘newpassword’ with your desired root password.

5) Exit MySQL

    • EXIT;

6) Stop the safe mode MySQL

    • sudo killall mysqld

(If it doesn’t stop, use sudo pkill -f mysqld_safe)

7) Start MySQL normally

    • sudo systemctl start mysql

8) Test the new password

    • mysql -u root -p
    • exit;

9) Reboot and check MySQL status

    • sudo reboot
    • log in
    • sudo systemctl status mysql

Conclusion

That’s it, your MySQL root password is now reset and everything should be back to normal. This method ensures security is preserved while giving you access again. Just be sure to store your new credentials somewhere safe.

 

 

How to Check Apache2 Logs on Ubuntu

Image : How to Check Apache2 Logs on Ubuntu

To view Apache 2 logs on Ubuntu, you can look in the /var/log/apache2 directory.

Here are the common log files you’ll want to check:

Access Logs

These logs contain information about requests that come to the Apache server. This log can contain client IP, requested URL, response status, and more.

Path: /var/log/apache2/access.log

View: sudo tail -f /var/log/apache2/access.log

Error Logs

This log file records any errors Apache encounters, including server misconfigurations, failed requests, or issues with the application running on the server.

Path: /var/log/apache2/error.log

View: sudo tail -f /var/log/apache2/error.log

Other Logs (Virtual Hosts)

If you’re using virtual hosts (for different websites hosted on the same server), you might have separate logs for each virtual host. These logs would be inside a subdirectory under “/var/log/apache2/”, such as “/var/log/apache2/your-site-name-access.log” and “/var/log/apache2/your-site-name-error.log“.

To actively monitor Apache logs, you can use “tail -f” to follow the logs in real-time. If you’re debugging something, this is very helpful.

Conclusion

Apache only has a few log files. For virtual host you will find logs for each virtual host. These normally come in the format of /var/log/apache2/your-site-name-access.log and /var/log/apache2/your-site-name-error.log.

How to Check Logs in Ubuntu Linux

Image : How to Check Logs in Ubuntu Linux

In Ubuntu Linux, logs are typically stored in the “/var/log/” directory. These logs can provide insights into system events, errors, and other important information. Here are some of the key log files and their uses:

auth.log

/var/log/auth.log: This log contains authentication-related events, such as login attempts and sudo commands.

To view: sudo less /var/log/auth.log

dmesg.log

/var/log/dmesg: This log stores kernel messages, which include hardware information and system boot details.

To view: sudo less /var/log/dmesg

faillog

/var/log/faillog: faillog is a system utility that tracks failed login attempts.

To view: sudo less /var/log/faillog

kern.log

/var/log/kern.log: This file contains kernel messages and can help diagnose low-level system problems.

To view: sudo less /var/log/kern.log

php8.x-fpm.log

/var/log/php8.x-fpm.log: This log file contains log messages generated by PHP-FPM related to the operation of PHP scripts running through it.

To view: sudo less /var/log/php8.x-fpm.log

syslog.log

/var/log/syslog: This is the general system log. It contains messages related to system activity and applications, and it’s a good place to start for troubleshooting.

To view: sudo less /var/log/syslog

ufw.log

/var/log/ufw.log: This log file is where UFW (Uncomplicated Firewall) records information about the firewall’s activity.

To view: sudo less /var/log/ufw.log

Conclusion

These 7 Ubuntu Linux logs can be used for system monitoring, troubleshooting, security, auditing, and debugging.

 

 

Apache Commands You Should Know

Image : Apache Commands You Should Know

Introduction

The Apache web server, serves content from a server to a browser. Apache is widely used on the the web. In this article I will cover most, if not all, of the Apache commands you will need to know.

Start Apache Service

    • sudo systemctl start apache2 # For Debian-based systems (Ubuntu)
    • sudo systemctl start httpd # For Red Hat-based systems (CentOS, Fedora)

Stop Apache Service

    • sudo systemctl stop apache2 # For Debian-based systems (Ubuntu
    • sudo systemctl stop httpd # For Red Hat-based systems (CentOS, Fedora)

Restart Apache Service

    • sudo systemctl restart apache2 # For Debian-based systems (Ubuntu)
    • sudo systemctl restart httpd # For Red Hat-based systems (CentOS, Fedora)

Reload Apache Configuration

    • sudo systemctl reload apache2 # For Debian-based systems (Ubuntu)
    • sudo systemctl reload httpd # For Red Hat-based systems (CentOS, Fedora)

Check Apache Status

    • sudo systemctl status apache2 # For Debian-based systems (Ubuntu)
    • sudo systemctl status httpd # For Red Hat-based systems (CentOS, Fedora)

Enable Apache to Start at Boot

    • sudo systemctl enable apache2 # For Debian-based systems (Ubuntu)
    • sudo systemctl enable httpd # For Red Hat-based systems (CentOS, Fedora)

Disable Apache to Start at Boot

    • sudo systemctl disable apache2 # For Debian-based systems (Ubuntu)
    • sudo systemctl disable httpd # For Red Hat-based systems (CentOS, Fedora)

Test Apache Configuration

    • apachectl configtest

Check Apache Version

    • apache2 -v # For Debian-based systems (Ubuntu)
    • httpd -v # For Red Hat-based systems (CentOS, Fedora)

Stop Apache Gracefully

    • sudo apachectl graceful

Run Apache in the Foreground (Debug Mode)

    • sudo apachectl -X

Disable a Site

    • sudo a2dissite [site-name] # For Debian-based systems (Ubuntu)

Enable a Site

sudo a2ensite [site-name] # For Debian-based systems (Ubuntu)

Check Apache Modules

apache2ctl -M # For Debian-based systems (Ubuntu)
httpd -M # For Red Hat-based systems (CentOS, Fedora)

Enable/Disable Apache Modules

sudo a2enmod [module_name] # Enable a module
sudo a2dismod [module_name] # Disable a module

Conclusion

These commands should help you effectively manage your Apache HTTP Server. Always ensure you have the proper permissions (often requiring sudo) to execute administrative actions.

Basic Linux Commands

Image : Basic Linux Commands

Introduction

This article is an introduction to many Linux command line commands. Each command has one or more arguments which I did not include.

This is not a comprehensive list, however this list will get you well on your way.

Here are some fundamental Linux commands that are essential for everyday use:

File and Directory Management:

    • ls – List directory contents
    • cd – Change directory
    • pwd – Print working directory (shows the current directory)
    • mkdir – Make a new directory
    • rmdir – Remove an empty directory
    • rm – Remove files or directories
    • cp – Copy files or directories
    • mv – Move or rename files or directories
    • touch – Create an empty file or update the timestamp of a file

File Viewing and Editing:

    • cat – Display file contents
    • more / less – View file contents page by page
    • head – Display the first few lines of a file
    • tail – Display the last few lines of a file

File Permissions and Ownership:

    • chmod – Change file permissions
    • chown – Change file owner and group
    • chgrp – Change the group ownership of a file

System Information:

    • df – Display disk space usage
    • du – Show disk usage of files and directories
    • top – Display system processes
    • ps – Show running processes
    • free – Show memory usage
    • uptime – Show how long the system has been running
    • uname – Show system information

Package Management (Debian-based systems like Ubuntu):

    • apt-get – Package management tool

Searching:

    • find – Search for files in a directory hierarchy
    • grep – Search for text patterns within files

Networking:

    • ping – Test network connectivity
    • ifconfig (or ip a) – Show network interface configuration
    • netstat – Show network connections
    • scp – Secure copy (copy files over SSH)

Archive and Compression:

    • tar – Create and extract tar archives
    • zip / unzip – Compress or decompress files

Other Useful Commands:

    • sudo – Execute a command as a superuser
    • man – Show the manual for a command
    • history – Show the history of previously executed commands
    • alias – Create custom command shortcuts

Conclusion

In this article we cover a lot of the Linux command line commands. This may not be a comprehensive list of Linux command, however the contents of this article will get you well on your way to managing Linux from the command line.

Linux File Permissions Explained

Image: Linux File Permissions Explained

Introduction

In this article and associated video, we will cover Linux file and directory ownership and permissions.

Every file and directory on a Linux system is associated with an owner and a group. This is how the system identifies who has control over the files and directories and who is part of the group that can access it.

    • Owner : The user who owns a file or directory. Customarily the owner has the ability to add/edit/delete files/directories and modify their permissions.
    • Group : A set of users who share the same permissions for a file or a directory.
    • Others : Everyone else who is not the owner or a member of the group.

1) Symbolic Notation : when permissions and users are represented by letters.

Permissions:

    • r” : Read
    • w” : Write
    • x” : Execute
    • +” : Add a permission
    • ” : Remove a permission
    • =” : Set exact permissions

Ownership:

    • Owner : u
    • Group : g
    • Others : o

Examples:

Add execute permission for the owner: $ chmod u+x file.txt

Remove write permission for others: $ chmod o-w file.txt

2) Numeric Notation

Each permission corresponds to a number:

    • r = 4” : read
    • w = 2” : write
    • x = 1” : execute

The permissions for each user (owner, group, others) are represented as a three-digit number.

    • 7” = “rwx” (read, write, execute)
    • 6” = “rw-” (read, write)
    • 5” = “r-x” (read, execute)
    • 4” = “r–” (read)
    • 3” = “-wx” (write, execute)
    • 2” = “w” (read)
    • 1” = “–x” (execute)
    • 0” = “” (no permissions)

To set permissions numerically, you add the values for owner, group, and others. For example:

File : $ chmod 644 file.txt

    • 6” (owner) = `rw-` (read, write)
    • 4” (group) = `r–` (read)
    • 4” (others) = `r–` (read)

Directory : $ chmod 755 <directory>

    • 7” (owner) = `rwx` (read, write, execute)
    • 5” (group) = `r-x` (read, execute)
    • 5” (others) = `r-x` (read, execute)

3) File Ownership

    • Owner : The user who owns a file.
    • Group : A set of users who share the same permissions for a file.
    • Others : Everyone else who is not the owner or a member of the group.

4) File Permissions

    • Read (r) : Permission to open and read the contents of a file.
    • Write (w) : Permission to modify or delete the contents of a file.
    • Execute (x) : Permission to execute a file (i.e., run it as a program).

5) Directory Ownership

Owner (User): Each directory in Linux is associated with an owner, which is typically a user. The owner has specific permissions to read, write, and execute files within that directory, depending on the permissions set. The owner is usually the user who created the directory, but ownership can be changed.

Group : In addition to the owner, a directory is associated with a group. The group defines a set of users who share common access rights to the directory. Group members can have different permission levels compared to the owner or other users.

Permissions

Linux uses three main types of permissions for directories:

    • Read (r) : The user can list the contents of the directory.
    • Write (w) : The user can create, delete, or rename files in the directory.
    • Execute (x) : The user can navigate into the directory and access files or subdirectories.

These permissions are assigned to three categories of users:

    • Owner: The user who owns the directory.
    • Group: Users who are members of the group assigned to the directory.
    • Others: All other users on the system.

6) Directory Permissions

    • Read (r) : for directories, this allows listing the files inside the directory.
    • Write (w) : for directories, this allows adding, deleting, or renaming files within the directory.
    • Execute (x): for directories, this allows accessing the directory, meaning the ability to enter the directory and work with its file.

7) Changing Ownership

To change the owner and group of a file or directory, you use the `chown` command.

Example : $ sudo chown <newuser>:<newgroup> file.txt (could be a directory).

8) Changing Permissions

To modify the permissions, you use the “chmod” command. Permissions can be set using symbolic notation (letters) or numeric notation (numbers).

    • Read (“r”) : Allows listing the contents.
    • Write (“w”) : Allows modifying the directory’s contents (adding/removing files).
    • Execute (“x”) : Allows accessing files inside the directory (entering the directory).

Example: sudo chmod 755 <directory> (could be a file)

9) Listing Permissions

File: One the command line issue the command “vdir”.

Directories: One the command line issue the command “vdir -id”.

Conclusion

This article and associated video cover Linux file and directory ownership and permissions and how to change them.

Changing file ownership and permissions can be completed by one of two approaches – Symbolic Notation or Numeric Notation.

To change file or directory ownership we use the chown command.

To change file or directory permissions we use the chmod command.

Introduction to The Linux vi Editor

Image : Introduction to The Linux vi Editor

What is Linux vi

vi is a powerful text editor that runs on Linux and UNIX systems, commonly used for editing configuration files, programming, and general text manipulation. It is known for its efficiency and speed once users are familiar with its commands.

vi is my editor of choice while I am connected to a web server via the Secure Shell (SSH). I am a PHP programmer and have a home lab that consists of using VirtualBox to create virtual machines. These virtual machines are web servers created for PHP development and testing. They are Linux, Apache, MySQL, and PHP (LAMP).

I use Ubuntu servers to create these LAMP web servers. Vi is one of the tools in my toolbox.

Why use vi?

Pre-installed: vi is usually available by default on almost all Linux distributions, making it convenient when working on servers or systems with minimal software installed.

Efficiency: vi allows advanced users to perform complex text editing tasks quickly and with precision.

Lightweight: It is a lightweight editor that consumes minimal system resources, which is ideal for working on remote servers or in environments with limited resources.

The best way to learn Vi is to create a new file and try it out for yourself.

1) VI Operates in Three Main Modes:

    • Normal Mode: This is the default mode. You can navigate and manipulate text using various commands.
    • Insert Mode: Add, Edit, Delete, and Copy text. Press the i key to activate insert mode. In insert mode, one can add, edit, delete, copy text, and move text around.
    • Command Mode: You enter this mode by pressing : (colon key) while in normal mode, to run commands like saving, quitting, or searching.

2) I Only Use a Subset of What is Available.

    • Type “vi <file-name>” on the command line to edit or create a file.
    • Pressing the “i” key switches us into Insert mode.
    • Pressing the “ESC” key switches us out of Insert mode into normal mode.
    • Pressing the “:” (colon) switches us into command mode.
    • dd command – Remove a line.
    • :q To quit when no changes have occurred.
    • :q! To not save changes.
    • :w Save and continue editing.
    • :wq To write (save) and quit (exit editing of file)
    • :set nu — Display line numbers.
    • :set nonu – Stop displaying line numbers.

3) Commands I Rarely or Never Use:

    • yy — Copy the current line. Referred to as yank(ed)
    • p — Paste the yanked line.
    • o — New line under the current line.
    • O — New line above the current line.
    • A — Append to the end of the line.
    • a — Append after the cursor’s current position.
    • I — Insert text at the beginning of the current line.
    • b — Go to the beginning of the word.
    • e — Go to the end of the word.
    • x — Delete a single character. (where the cursor is blinking)
    • dd — Delete the current line.
    • [number]dd — Delete X number of lines.
    • [number]yy — Yank X number of lines.
    • G — Go to the end of the file.
    • XG — Go to line X in a file.
    • gg — Go to the first line in a file.
    • h — Move left one character.
    • j — Move down one line.
    • k — Move up one line.
    • l — Move right one character.

Conclusion

Vi is the editor I like to use when connected to a remote server. I manage virtual web hosts on VirtualBox. Vi makes it easy to manage all the configurations a LAMP server contains.

In this article we learned that vi has Three Main Mode, is always available on Linux and Unix servers, and is easy to use once some of the features are understood.

 

How to Add PHP-FPM Support on Apache2/Ubuntu 24.04 LTS

Image : How to Add PHP-FPM Support on Apache2/Ubuntu 24.04 LTS

Introduction

I am a PHP developer. I use Linux, Apache, MySQL, and PHP (LAMP) to further that goal.

I have published a number of YouTube videos and blog posts that document configuring a LAMP server for development and testing.

I am using an older HP laptop that is running Windows 10. On that, I have installed VirtualBox.

VirtualBox is a type two hypervisor that allows me to create virtual machines.

In this context, Linux is the operating system of the web server. Most PHP websites run on Linux web servers and are configured as a LAMP stack.

Apache serves web pages to users who request them via browsers, handling HTTP requests and delivering the corresponding web content (HTML files, images, etc.) from a server to a client (usually a web browser).

MySQL is an open-source relational database management system (RDBMS) that uses Structured Query Language (SQL) to manage and interact with databases. It is widely used for storing and retrieving data in a variety of applications, from web development to enterprise-level solutions.

PHP (Hypertext Preprocessor) is a popular general-purpose scripting language that is especially suited to web development. It is a server-side language, meaning that it runs on a web server rather than in the user’s browser, allowing developers to create dynamic web pages and other content.

I have created a private network in my home office. This network uses private non-routable IP addresses and private non-routable domain names.

I have configured two virtual hosts on my server:

1) default.internal.
2) lamp.internal.

I have created two users:

1) default.
2) lamp.

The user named default is the owner of the virtual host that is created by Apache when Apache is installed. This virtual host is incomplete. I completed the virtual host configuration so I can use it as a model for the virtual hosts I will build in the future. This virtual host can be accessed by a browser by using the private domain, default.internal.

The user named lamp is the owner of the lamp virtual host and is accessed by a browser using the private domain lamp.internal.

Both users were configured to allow them to use SSH (Secure Shell).

I am configuring my server this way so I can access the virtual host remotely with the ability to create, read, update, and delete files and directories on the remote server.

To complete the goal of remote editing we need to install and configure PHP-FPM. PHP-FPM stands for PHP FastCGI Process Manager.

SPM will enhance the performance of an Apache web server, however I am using it to enable the ability for remote editing.

My daily driver is a 10 year old Dell that is running Kunbuntu (Linux). Native to Kunbuntu is the Linux terminal that allows me to access a remote server. I also have installed Visual Studio Code on this computer which allows for remote editing of PHP code.

Even though VirtualBox is running on my laptop running Windows 10, any virtual server created using VirtualBox is remote to that Windows configuration.

We start by installing and configuring PHP-FPM. This install is only required once.

In the 2nd part, I will configure an Apache virtual host to take advantage of PHP-FPM.

After completing part 1, any time you want to configure an Apache virtual host to take advantage of the PHP-FPM install, you will only need to follow the 2nd part – where I configure an Apache host to use PHP-FPM.

**********************************************************
**********************************************************
***     Install and Activate PHP-FPM ONLY     ***
**********************************************************
**********************************************************

To install, activate, start, and configure PHP-FPM on Ubuntu 24.04 LTS without modifying Apache2 configuration or vhost settings, you can follow these steps. This will ensure that PHP-FPM is running and available for use without interfering with Apache’s default settings.

Step 1: Upgrade and Update all of the server packages

– sudo apt update
– sudo apt upgrade
– sudo apt autoremove
– sudo reboot

Step 2: Install PHP-FPM:

– sudo apt install php-fpm

Step 3: Enable the proxy_fcgi and setenvif modules:

– sudo a2enmod proxy_fcgi setenvif
– sudo systemctl restart apache2

Step 4: Enable the configuration file for PHP-FPM (FastCGI Process Manager):

– sudo a2enconf php8.3-fpm

Step 5: Reload apache2:

– sudo systemctl reload apache2

Step 6: Check PHP-FPM Service Status:

– sudo systemctl status php8.3-fpm

Step 7: Enable it to start on boot:

– sudo systemctl enable php8.3-fpm

Step 8: Restart Apache and PHP-FPM for the changes to take effect:

– sudo systemctl restart apache2
– sudo systemctl restart php8.3-fpm

Step 9: Verify PHP-FPM is Working:

– sudo systemctl status php8.3-fpm

– – – – – – – – – – – – – – – – – –
– – – – – END – – – – – – – – –
– – – – – – – – – – – – – – – – – –

*****************************************************************************
*****************************************************************************
*****     Configure Apache Virtual Host to Use PHP-FPM     *****
*****************************************************************************
*****************************************************************************

Step 1: Define how a PHP file should be handled by the server.

– sudo vi /etc/apache2/sites-available/lamp.internal.conf

– ADD :

<FilesMatch \.php$>
SetHandler "proxy:unix:/var/run/php/php8.3-fpm.lamp.sock|fcgi://localhost/"
</FilesMatch>

Step 2: Create the configuration file for the lamp user:

– sudo vi /etc/php/8.3/fpm/pool.d/lamp.conf

Add the following content:

[lamp] ; Define the pool name, which will be referenced by PHP-FPM
user = lamp ; Set the user under which PHP-FPM will run
group = lamp ; Set the group under which PHP-FPM will run
listen = /run/php/php8.3-fpm.lamp.sock ; Define the socket path for the pool (for communication with the web server)
listen.owner = www-data ; Set the owner of the socket file
listen.group = www-data ; Set the group of the socket file
listen.mode = 0660 ; Set the permissions for the socket file (660 = read/write for owner/group)
pm = dynamic ; Enable dynamic process management (adjusts worker count based on demand)
pm.max_children = 50 ; Maximum number of child processes to handle requests
pm.start_servers = 5 ; Number of child processes created on startup
pm.min_spare_servers = 5 ; Minimum number of idle servers to keep alive
pm.max_spare_servers = 10 ; Maximum number of idle servers to keep alive
pm.max_requests = 5000 ; The maximum number of requests a child process should handle before being restarted
php_admin_value[error_log] = /var/log/php8.3-fpm/lamp_error.log ; Set a custom error log for this pool
php_admin_value[log_errors] = on ; Enable error logging
env[PATH] = /usr/local/bin:/usr/bin:/bin ; Define the environment variables (add more if needed)

** The bolded values should be changed to the user for the virtual host you are configuring.

** Remove all spaces from the left of this code or you will receive an error.

Step 3: Set ownership, permissions, and home directory

– sudo chown -R lamp:lamp /var/www/lamp.internal
– sudo find /var/www/lamp.internal -type d -exec chmod 755 {} \;
– sudo find /var/www/lamp.internal -type f -exec chmod 644 {} \;
– sudo usermod -d /var/www/lamp.internal/public_html lamp

Step 4: Enable the configuration for this virtual host:

– sudo a2ensite lamp.internal.conf

Step 5: Restart PHP-FPM and Apache to apply the changes.

– sudo systemctl restart php8.3-fpm
– sudo systemctl restart apache2

Step 6: Test the Apache configuration:

– sudo apache2ctl configtest

Step 7: Ensure that both domains are configured correctly and accessible in your browser:

– Make sure the site is viewable in a browser : http://lamp.internal/info.php
– Look for “Server API” with the value: “FPM/FastCGI”
– Connect via Filezilla.
– Use PuTTy or a Linux Konsole  to verify the SSH connection is working.
– Use Visual Studio Code to verify that code can be edited.
– Use Visual Studio to create a PHP script that will create a text file, proving PHP is working correctly under PHP-FPM: Using Visual Studio code create  a new file and name it : php-tester.php. Copy and paste the following code into that file and save it.  Then run it in your browser : http://lamp.internal/php-tester.php

<?php
// The name of the file to be created
$filename = "test_file.txt";
// Open the file for writing (creates file if it
doesn't exist)
$file = fopen($filename, "w");
// Check if the file is created successfully
if ($file) {
fwrite($file, "This file was created by PHP!");
fclose($file);
echo "File '$filename' was successfully created!";
} else {
echo "Failed to create the file.";
}
?>

– If all is working as expected you should find a file by the name
of test_file.txt with the contents of  “This file was created by PHP!”.

Conclusion

In this article we covered how to install PHP-FPM and configure it to work with an Apache virtual host.

PHP-FPM serves two purposes: 1) is it a performance enhancer, 2) it provides a way for us to remote edit our PHP code directly on the server.

Installing and configuring PHP-FPM is only required once. That would be the first part which consists of 9 steps.

The second set of 7 steps has to be completed every time you want to configure a new virtual host.

How to Change the Home Directory of a New or Existing User on Ubuntu 24.04LTS

Image: How to Change the Home Directory of an New or Existing User on Ubuntu 24.04lts

I do this so I will land in the docroot of the virtual host when using SSH, FileZilla, and/or Visual Studio Code. This configuration aids me when I want to edit PHP remotrely using Visual Studio Code.

The command sudo usermod -d is used to change the home directory of a user on a Unix-like operating system. In this case I use this command on Ubuntu 24.04LTS.

Here’s a Breakdown of the Command

sudo: This command runs the following command with superuser (root) privileges, which are often necessary for modifying user accounts.

usermod: This is the command used to modify user account settings.

-d <directory-path>: This option specifies the new home directory for the user.

username: This is the placeholder for the actual username of the account whose home directory you want to change.

Apache configures a default virtual host as part of the initial installation. This virtual host is incomplete as a virtual host. I completed the build of the default Apache virtual host.

As part of the build out I added a user named default and changed it’s home directory to /var/www/html by the following command:

– sudo usermod -d /var/www/html default

Key Points

Changing Home Directory: This command changes where the user’s files and settings are stored. By default, a user’s home directory is often located in /home/username.

Permissions: Ensure that the new directory (<directory-path>) has the appropriate permissions for the user to access and manage files there.

Impact: Changing the home directory can affect scripts, applications, and settings that rely on the old home directory path.

Make sure to back up any important data before making such changes.