Setting Up a LAMP Server on VPS Ubuntu (Apache2)

Setting Up a LAMP Server on VPS Ubuntu (Apache2)

In the realm of web development, mastering the setup of a LAMP (Linux, Apache, MySQL, PHP) server on Ubuntu is a fundamental skill. This concise guide walks you through the essential steps to establish a robust foundation for hosting dynamic web applications and websites. By following these instructions, you'll be equipped to unleash your creativity and innovation in the digital space with confidence. Let's dive in and demystify the process of configuring your own LAMP server on Ubuntu.

  1. Install Apache & Update Firewall
  2. Install MySQL Database
  3. Setup phpMyAdmin
  4. Install PHP
  5. Install Composer
  6. Install Node, NVM, pm2
  7. Setup Virtual Webhost

Step 1 — Installing Apache and Updating the Firewall

The Apache web server is among the most popular web servers in the world. It’s well documented, has an active community of users, and has been in wide use for much of the history of the web, which makes it a great choice for hosting a website.

sudo apt update        

Then, install Apache with:

sudo apt install apache2        

You’ll be prompted to confirm Apache’s installation. Confirm by pressing Y, then.

Once the installation is finished, you’ll need to adjust your firewall settings to allow HTTP traffic. Ubuntu’s default firewall configuration tool is called Uncomplicated Firewall (UFW). It has different application profiles that you can leverage. To list all currently available UFW application profiles, execute this command:

sudo ufw app list        
OutputAvailable applications:
  Apache
  Apache Full
  Apache Secure
  OpenSSH        

Here’s what each of these profiles mean:

  • Apache: This profile opens only port 80 (normal, unencrypted web traffic).
  • Apache Full: This profile opens both port 80 (normal, unencrypted web traffic) and port 443 (TLS/SSL encrypted traffic).
  • Apache Secure: This profile opens only port 443 (TLS/SSL encrypted traffic).

For now, it’s best to allow only connections on port 80, since this is a fresh Apache installation and you don’t yet have a TLS/SSL certificate configured to allow for HTTPS traffic on your server.

To only allow traffic on port 80, use the Apache profile:

sudo ufw allow in "Apache"        

Verify the change with:

sudo ufw status        
OutputStatus: active

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

Step 2 — Installing MySQL

Now that you have a web server up and running, you need to install the database system to be able to store and manage data for your site. MySQL is a popular database management system used within PHP environments.

Again, use apt to acquire and install this software:

sudo apt install mysql-server        

When prompted, confirm installation by typing Y, and then ENTER.

When the installation is finished, it’s recommended that you run a security script that comes pre-installed with MySQL. This script will remove some insecure default settings and lock down access to your database system.

Because the mysql_secure_installation script performs a number of other actions that are useful for keeping your MySQL installation secure, it’s still recommended that you run it before you begin using MySQL to manage your data. To avoid entering this recursive loop, though, you’ll need to first adjust how your root MySQL user authenticates.

First, open up the MySQL prompt:

sudo mysql        

Then run the following ALTER USER command to change the root user’s authentication method to one that uses a password. The following example changes the authentication method to mysql_native_password:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';        

After making this change, exit the MySQL prompt:

exit        

Following that, you can run the mysql_secure_installation script without issue.

Start the interactive script by running:

sudo mysql_secure_installation        

This will ask if you want to configure the VALIDATE PASSWORD PLUGIN.

Answer Y for yes, or anything else to continue without enabling.

VALIDATE PASSWORD PLUGIN can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD plugin?

Press y|Y for Yes, any other key for No:
        

If you answer “yes”, you’ll be asked to select a level of password validation. Keep in mind that if you enter 2 for the strongest level, you will receive errors when attempting to set any password which does not contain numbers, upper and lowercase letters, and special characters:

There are three levels of password validation policy:

LOW    Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary              file

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 1
        

Regardless of whether you chose to set up the VALIDATE PASSWORD PLUGIN, your server will next ask you to select and confirm a password for the MySQL root user. This is not to be confused with the system root. The database root user is an administrative user with full privileges over the database system. Even though the default authentication method for the MySQL root user doesn’t involve using a password, even when one is set, you should define a strong password here as an additional safety measure.

If you enabled password validation, you’ll be shown the password strength for the root password you just entered and your server will ask if you want to continue with that password. If you are happy with your current password, enter Y for “yes” at the prompt:

Estimated strength of the password: 100
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y        

For the rest of the questions, press Y and hit the ENTER key at each prompt. This will remove some anonymous users and the test database, disable remote root logins, and load these new rules so that MySQL immediately respects the changes you have made.

When you’re finished, test whether you’re able to log in to the MySQL console by typing:

sudo mysql        

This will connect to the MySQL server as the administrative database user root, which is inferred by the use of sudo when running this command. Below is an example output:

OutputWelcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.28-0ubuntu4 (Ubuntu)

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>
        

To exit the MySQL console, type:

exit        

Step 3 — Installing phpMyAdmin

You can use APT to install phpMyAdmin from the default Ubuntu repositories.

Run the following command to install these packages onto your system. Please note, though, that the installation process requires you to make some choices to configure phpMyAdmin correctly. We’ll walk through these options shortly:

sudo apt install phpmyadmin php-mbstring php-zip php-gd php-json php-curl        

Here are the options you should choose when prompted in order to configure your installation correctly:

  • For the server selection, choose apache2

Warning: When the 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.

  • Select Yes when asked whether to use dbconfig-common to set up the database
  • You will then be asked to choose and confirm a MySQL application password for phpMyAdmin

To resolve this, select the abort option to stop the installation process. Then, open up your MySQL prompt:

sudo mysql        

Or, if you enabled password authentication for the root MySQL user, run this command and then enter your password when prompted:

mysql -u root -p        

From the prompt, run the following command to disable the Validate Password component. Note that this won’t actually uninstall it, but just stop the component from being loaded on your MySQL server:

UNINSTALL COMPONENT "file://component_validate_password";        

Following that, you can close the MySQL client:

exit        

Then try installing the phpmyadmin package again and it will work as expected:

sudo apt install phpmyadmin        

Once phpMyAdmin is installed, you can open the MySQL prompt once again with sudo mysql or mysql -u root -p and then run the following command to re-enable the Validate Password component:

INSTALL COMPONENT "file://component_validate_password";        

The installation process adds the phpMyAdmin Apache configuration file into the /etc/apache2/conf-enabled/ directory, where it is read automatically. To finish configuring Apache and PHP to work with phpMyAdmin, the only remaining task in this section of the tutorial is to is explicitly enable the mbstring PHP extension, which you can do by typing:

sudo phpenmod mbstring        

Afterwards, restart Apache for your changes to be recognized:

sudo systemctl restart apache2        

Configuring Password Access for the MySQL Root Account

In order to log in to phpMyAdmin as your root MySQL user, you will need to switch its authentication method from auth_socket to one that makes use of a password, if you haven’t already done so. To do this, open up the MySQL prompt from your terminal:

sudo mysql        

Next, check which authentication method each of your MySQL user accounts use with the following command:

SELECT user,authentication_string,plugin,host FROM mysql.user;        
Output+------------------+-------------------------------------------+-----------------------+-----------+
| user             | authentication_string                     | plugin                | host      |
+------------------+-------------------------------------------+-----------------------+-----------+
| root             |                                           | auth_socket           | localhost |
| mysql.session    | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | caching_sha2_password | localhost |
| mysql.sys        | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | caching_sha2_password | localhost |
| debian-sys-maint | *8486437DE5F65ADC4A4B001CA591363B64746D4C | caching_sha2_password | localhost |
| phpmyadmin       | *5FD2B7524254B7F81B32873B1EA6D681503A5CA9 | caching_sha2_password | localhost |
+------------------+-------------------------------------------+-----------------------+-----------+
5 rows in set (0.00 sec)        

o configure the root account to authenticate with a password, run the following ALTER USER command. Be sure to change password to a strong password of your choosing:

ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'password';
        

Note: The previous ALTER USER statement sets the root MySQL user to authenticate with the caching_sha2_password plugin. Per the official MySQL documentation, caching_sha2_password is MySQL’s preferred authentication plugin, as it provides more secure password encryption than the older, but still widely used, mysql_native_password.

However, some versions of PHP don’t work reliably with caching_sha2_password. PHP has reported that this issue was fixed as of PHP 7.4, but if you encounter an error when trying to log in to phpMyAdmin later on, you may want to set root to authenticate with mysql_native_password instead:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
        

Then, check the authentication methods employed by each of your users again to confirm that root no longer authenticates using the auth_socket plugin:

SELECT user,authentication_string,plugin,host FROM mysql.user;        
Output+------------------+-------------------------------------------+-----------------------+-----------+
| user             | authentication_string                     | plugin                | host      |
+------------------+-------------------------------------------+-----------------------+-----------+
| root             | *DE06E242B88EFB1FE4B5083587C260BACB2A6158 | caching_sha2_password | localhost |
| mysql.session    | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | caching_sha2_password | localhost |
| mysql.sys        | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | caching_sha2_password | localhost |
| debian-sys-maint | *8486437DE5F65ADC4A4B001CA591363B64746D4C | caching_sha2_password | localhost |
| phpmyadmin       | *5FD2B7524254B7F81B32873B1EA6D681503A5CA9 | caching_sha2_password | localhost |
+------------------+-------------------------------------------+-----------------------+-----------+
5 rows in set (0.00 sec)
        

You can see from this output that the root user will authenticate using a password. You can now log in to the phpMyAdmin interface as your root user with the password you’ve set for it here.

Configuring Password Access for a Dedicated MySQL User

Alternatively, some may find that it better suits their workflow to connect to phpMyAdmin with a dedicated user. To do this, open up the MySQL shell once again:

sudo mysql        

If you have password authentication enabled for your root user, as described in the previous section, you will need to run the following command and enter your password when prompted in order to connect:

mysql -u root -p        

From there, create a new user and give it a strong password:

CREATE USER 'sammy'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'password';        

Note: Again, depending on what version of PHP you have installed, you may want to set your new user to authenticate with mysql_native_password instead of caching_sha2_password:

ALTER USER 'sammy'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';        

Then, grant your new user appropriate privileges. For example, you could grant the user privileges to all tables within the database, as well as the power to add, change, and remove user privileges, with this command:

GRANT ALL PRIVILEGES ON *.* TO 'sammy'@'localhost' WITH GRANT OPTION;        

Following that, exit the MySQL shell:

exit        

You can now access the web interface by visiting your server’s domain name or public IP address followed by /phpmyadmin:

https://your_domain_or_IP/phpmyadmin        

Log in to the interface, either as root or with the new username and password you just configured.

When you log in, you’ll see the user interface, which will look something like this:

Now that you’re able to connect and interact with phpMyAdmin, all that’s left to do is harden your system’s security to protect it from attackers.

Securing Your phpMyAdmin Instance

Because of its ubiquity, phpMyAdmin is a popular target for attackers, and you should take extra care to prevent unauthorized access. One way of doing this is to place a gateway in front of the entire application by using Apache’s built-in .htaccess authentication and authorization functionalities.

To do this, you must first enable the use of .htaccess file overrides by editing your phpMyAdmin installation’s Apache configuration file.

Use your preferred text editor to edit the phpmyadmin.conf file that has been placed in your Apache configuration directory. Here, we’ll use nano:

sudo nano /etc/apache2/conf-available/phpmyadmin.conf        

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

/etc/apache2/conf-available/phpmyadmin.conf

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

When you have added this line, save and close the file. If you used nano to edit the file, do so by pressing CTRL + X, Y, and then ENTER.

To implement the changes you made, restart Apache:

sudo systemctl restart apache2        

Now that you have enabled the use of .htaccess files for your application, you 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. You can create the necessary file and open it in your text editor with root privileges by typing:

sudo nano /usr/share/phpmyadmin/.htaccess        

Within this file, enter the following information:

/usr/share/phpmyadmin/.htaccess

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

Here is what each of these lines mean:

  • AuthType Basic: This line specifies the authentication type that you 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.

When you are finished, save and close the file.

The location that you selected for your password file was /etc/phpmyadmin/.htpasswd. You can now create this file and pass it an initial user with the htpasswd utility:

sudo htpasswd -c /etc/phpmyadmin/.htpasswd 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        

Then restart Apache to put .htaccess authentication into effect:

sudo systemctl restart apache2        

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        

After entering the Apache authentication, you’ll be taken to the regular phpMyAdmin authentication page to enter your MySQL credentials.

Step 4 — Installing PHP

You have Apache installed to serve your content and MySQL installed to store and manage your data. PHP is the component of our setup that will process code to display dynamic content to the final user. In addition to the php package, you’ll need php-mysql, a PHP module that allows PHP to communicate with MySQL-based databases. You’ll also need libapache2-mod-php to enable Apache to handle PHP files. Core PHP packages will automatically be installed as dependencies.

To install these packages, run the following command:

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

Once the installation is finished, run the following command to confirm your PHP version:

php -v        
OutputPHP 8.1.2 (cli) (built: Mar  4 2022 18:13:46) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.2, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.2, Copyright (c), by Zend Technologies
        

Changing Apache’s Directory Index (Optional)

In some cases, you’ll want to modify the way that Apache serves files when a directory is requested. Currently, if a user requests a directory from the server, Apache will first look for a file called index.html. We want to tell the web server to prefer PHP files over others, to make Apache look for an index.php file first. If you don’t do that, an index.html file placed in the document root of the application will always take precedence over an index.php file.

To make this change, open the dir.conf configuration file in a text editor of your choice. Here, we’ll use nano:

sudo nano /etc/apache2/mods-enabled/dir.conf        

It will look like this:

/etc/apache2/mods-enabled/dir.conf

<IfModule mod_dir.c>
    DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm
</IfModule>
        

Move the PHP index file (highlighted above) to the first position after the DirectoryIndex specification, like this:

/etc/apache2/mods-enabled/dir.conf

<IfModule mod_dir.c>
    DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>
        

When you are finished, save and close the file by pressing CTRL+X. Confirm the save by typing Y and then hit ENTER to verify the file save location.

After this, restart the Apache web server in order for your changes to be recognized. You can do that with the following command:

sudo systemctl restart apache2        

You can also check on the status of the apache2 service using systemctl:

sudo systemctl status apache2        
Sample Output● apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
  Drop-In: /lib/systemd/system/apache2.service.d
           └─apache2-systemd.conf
   Active: active (running) since Thu 2021-07-15 09:22:59 UTC; 1h 3min ago
 Main PID: 3719 (apache2)
    Tasks: 55 (limit: 2361)
   CGroup: /system.slice/apache2.service
           ├─3719 /usr/sbin/apache2 -k start
           ├─3721 /usr/sbin/apache2 -k start
           └─3722 /usr/sbin/apache2 -k start

Jul 15 09:22:59 ubuntu1804 systemd[1]: Starting The Apache HTTP Server...
Jul 15 09:22:59 ubuntu1804 apachectl[3694]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' di
Jul 15 09:22:59 ubuntu1804 systemd[1]: Started The Apache HTTP Server.
        

Press Q to exit this status output.

Installing PHP Extensions (Optional)

To extend the functionality of PHP, you have the option to install some additional modules. To see the available options for PHP modules and libraries, pipe the results of apt search into less, a pager which lets you scroll through the output of other commands:

apt search php- | less        

Use the arrow keys to scroll up and down, and press Q to quit.

The results are all optional components that you can install. It will give you a short description for each:

bandwidthd-pgsql/bionic 2.0.1+cvs20090917-10ubuntu1 amd64
  Tracks usage of TCP/IP and builds html files with graphs

bluefish/bionic 2.2.10-1 amd64
  advanced Gtk+ text editor for web and software development

cacti/bionic 1.1.38+ds1-1 all
  web interface for graphing of monitoring systems

ganglia-webfrontend/bionic 3.6.1-3 all
  cluster monitoring toolkit - web front-end

golang-github-unknwon-cae-dev/bionic 0.0~git20160715.0.c6aac99-4 all
  PHP-like Compression and Archive Extensions in Go

haserl/bionic 0.9.35-2 amd64
  CGI scripting program for embedded environments

kdevelop-php-docs/bionic 5.2.1-1ubuntu2 all
  transitional package for kdevelop-php

kdevelop-php-docs-l10n/bionic 5.2.1-1ubuntu2 all
  transitional package for kdevelop-php-l10n
…
:
        

To learn more about what each module does, you could search the internet for more information about them. Alternatively, look at the long description of the package by typing:

apt show package_name        

There will be a lot of output, with one field called Description which will have a longer explanation of the functionality that the module provides.

For example, to find out what the php-cli module does, you could type this:

apt show php-cli        

Along with a large amount of other information, you’ll find something that looks like this:

Output…
Description: command-line interpreter for the PHP scripting language (default)
 This package provides the /usr/bin/php command interpreter, useful for
 testing PHP scripts from a shell or performing general shell scripting tasks.
 .
 PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used
 open source general-purpose scripting language that is especially suited
 for web development and can be embedded into HTML.
 .
 This package is a dependency package, which depends on Ubuntu's default
 PHP version (currently 7.2).
…
        

If, after researching, you decide you would like to install a package, you can do so by using the apt install command like you have been doing for the other software.

If you decided that php-cli is something that you need, you could type:

sudo apt install php-cli        

If you want to install more than one module, you can do that by listing each one, separated by a space, following the apt install command, like this:

sudo apt install package1 package2 ...        

At this point, your LAMP stack is installed and configured. Before you do anything else, we recommend that you set up an Apache virtual host where you can store your server’s configuration details.

Step 5 — Downloading and Installing Composer

Composer provides an installer script written in PHP. We’ll download it, verify that it’s not corrupted, and then use it to install Composer.

Make sure you’re in your home directory, then retrieve the installer using curl:

cd ~
curl -sS https://getcomposer.org/installer -o /tmp/composer-setup.php        

Next, we’ll verify that the downloaded installer matches the SHA-384 hash for the latest installer found on the Composer Public Keys / Signatures page. To facilitate the verification step, you can use the following command to programmatically obtain the latest hash from the Composer page and store it in a shell variable:

HASH=`curl -sS https://composer.github.io/installer.sig`        

If you want to verify the obtained value, you can run:

echo $HASH        
Outpute0012edf3e80b6978849f5eff0d4b4e4c79ff1609dd1e613307e16318854d24ae64f26d17af3ef0bf7cfb710ca74755a
        

Now execute the following PHP code, as provided in the Composer download page, to verify that the installation script is safe to run:

php -r "if (hash_file('SHA384', '/tmp/composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"        

You’ll see the following output:

Output

Installer verified        

If the output says Installer corrupt, you’ll need to download the installation script again and double check that you’re using the correct hash. Then, repeat the verification process. When you have a verified installer, you can continue.

To install composer globally, use the following command which will download and install Composer as a system-wide command named composer, under /usr/local/bin:

sudo php /tmp/composer-setup.php --install-dir=/usr/local/bin --filename=composer        

You’ll see output similar to this:

OutputAll settings correct for using Composer
Downloading...

Composer (version 2.2.9) successfully installed to: /usr/local/bin/composer
Use it: php /usr/local/bin/composer
        

To test your installation, run:

composer        
Output   ______
  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version Composer version 2.2.9 2022-03-15 22:13:37
Usage:
  command [options] [arguments]

Options:
  -h, --help                     Display this help message
  -q, --quiet                    Do not output any message
  -V, --version                  Display this application version
      --ansi                     Force ANSI output
      --no-ansi                  Disable ANSI output
  -n, --no-interaction           Do not ask any interactive question
      --profile                  Display timing and memory usage information
      --no-plugins               Whether to disable plugins.
  -d, --working-dir=WORKING-DIR  If specified, use the given directory as working directory.
      --no-cache                 Prevent use of the cache
  -v|vv|vvv, --verbose           Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
...
        

This verifies that Composer was successfully installed on your system and is available system-wide.

Step 6 — Installing Node Using the Node Version Manager

Another way of installing Node.js that is particularly flexible is to use nvm, the Node Version Manager. This piece of software allows you to install and maintain many different independent versions of Node.js, and their associated Node packages, at the same time.

You can do that by removing the | bash segment at the end of the curl command:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh        

Review the script and make sure you are comfortable with the changes it is making. When you are satisfied, run the command again with | bash appended at the end. The URL you use will change depending on the latest version of nvm, but as of right now, the script can be downloaded and executed with the following:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash        

This will install the nvm script to your user account. To use it, you must first source your .bashrc file:

source ~/.bashrc        

Now, you can ask NVM which versions of Node are available:

nvm list-remote        
Output. . .
        v18.0.0
        v18.1.0
        v18.2.0
        v18.3.0
        v18.4.0
        v18.5.0
        v18.6.0
        v18.7.0
        v18.8.0
        v18.9.0
        v18.9.1
       v18.10.0
       v18.11.0
       v18.12.0   (LTS: Hydrogen)
       v18.12.1   (LTS: Hydrogen)
       v18.13.0   (Latest LTS: Hydrogen)
        v19.0.0
        v19.0.1
        v19.1.0
        v19.2.0
        v19.3.0
        v19.4.0
        

It’s a very long list. You can install a version of Node by writing in any of the release versions listed. For instance, to get version v14.10.0, you can run:

nvm install v20.10.0        

You can view the different versions you have installed by listing them:

nvm list
        
Output->     v20.10.0
       v14.21.2
default -> v14.10.0
iojs -> N/A (default)
unstable -> N/A (default)
node -> stable (-> v14.21.2) (default)
stable -> 14.21 (-> v14.21.2) (default)
. . .
        

This shows the currently active version on the first line (-> v20.10.0), followed by some named aliases and the versions that those aliases point to.

Install PM2 by typing thr following at the command line:

sudo npm install pm2 -g        

Step 7 — Creating a Virtual Host for your Website

When using the Apache web server, you can create virtual hosts (similar to server blocks in Nginx) to encapsulate configuration details and host more than one domain from a single server. In this guide, we’ll set up a domain called your_domain, but you should replace this with your own domain name.

Apache on Ubuntu has one virtual host enabled by default that is configured to serve documents from the /var/www/html directory. While this works well for a single site, it can become unwieldy if you are hosting multiple sites. Instead of modifying /var/www/html, we’ll create a directory structure within /var/www for the your_domain site, leaving /var/www/html in place as the default directory to be served if a client request doesn’t match any other sites.

Create the directory for your_domain as follows:

sudo mkdir /var/www/your_domain        

Next, assign ownership of the directory with the $USER environment variable, which will reference your current system user:

sudo chown -R $USER:$USER /var/www/your_domain        

Then, open a new configuration file in Apache’s sites-available directory using your preferred command-line editor. Here, we’ll use nano:

sudo nano /etc/apache2/sites-available/your_domain.conf        

This will create a new blank file. Add in the following bare-bones configuration with your own domain name:

/etc/apache2/sites-available/your_domain.conf

<VirtualHost *:80>
    ServerName your_domain
    ServerAlias www.your_domain
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/your_domain
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
        

Save and close the file when you’re done. If you’re using nano, do that by pressing CTRL+X, then Y and ENTER.

With this VirtualHost configuration, we’re telling Apache to serve your_domain using /var/www/your_domain as the web root directory. If you’d like to test Apache without a domain name, you can remove or comment out the options ServerName and ServerAlias by adding a pound sign (#) the beginning of each option’s lines.

Now, use a2ensite to enable the new virtual host:

sudo a2ensite your_domain        

You might want to disable the default website that comes installed with Apache. This is required if you’re not using a custom domain name, because in this case Apache’s default configuration would override your virtual host. To disable Apache’s default website, type:

sudo a2dissite 000-default        

To make sure your configuration file doesn’t contain syntax errors, run the following command:

sudo apache2ctl configtest        

Finally, reload Apache so these changes take effect:

sudo systemctl reload apache2        

Your new website is now active, but the web root /var/www/your_domain is still empty. Create an index.html file in that location to test that the virtual host works as expected:

nano /var/www/your_domain/index.html        

Include the following content in this file:

/var/www/your_domain/index.html

<html>
  <head>
    <title>your_domain website</title>
  </head>
  <body>
    <h1>Hello World!</h1>

    <p>This is the landing page of <strong>your_domain</strong>.</p>
  </body>
</html>
        

Save and close the file, then go to your browser and access your server’s domain name or IP address:

https://server_domain_or_IP        

Your web page should reflect the contents in the file you just edited:

You can leave this file in place as a temporary landing page for your application until you set up an index.php file to replace it. Once you do that, remember to remove or rename the index.html file from your document root, as it would take precedence over an index.php file by default.

With the default DirectoryIndex settings on Apache, a file named index.html will always take precedence over an index.php file.

In case you want to change this behavior, you’ll need to edit the /etc/apache2/mods-enabled/dir.conf file and modify the order in which the index.php file is listed within the DirectoryIndex directive:

sudo nano /etc/apache2/mods-enabled/dir.conf        

/etc/apache2/mods-enabled/dir.conf

<IfModule mod_dir.c>
        DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>
        

After saving and closing the file, you’ll need to reload Apache so the changes take effect:

sudo systemctl reload apache2        

In the next step, we’ll create a PHP script to test that PHP is correctly installed and configured on your server.

Testing PHP Processing on your Web Server

Now that you have a custom location to host your website’s files and folders, create a PHP test script to confirm that Apache is able to handle and process requests for PHP files.

Create a new file named info.php inside your custom web root folder:

nano /var/www/your_domain/info.php        

This will open a blank file. Add the following text, which is valid PHP code, inside the file:

/var/www/your_domain/info.php

<?php
phpinfo();        

When you are finished, save and close the file.

To test this script, go to your web browser and access your server’s domain name or IP address, followed by the script name, which in this case is info.php:

https://server_domain_or_IP/info.php        

Here is an example of the default PHP web page:

This page provides information about your server from the perspective of PHP. It is useful for debugging and to ensure that your settings are being applied correctly.

If you see this page in your browser, then your PHP installation is working as expected.

After checking the relevant information about your PHP server through that page, it’s best to remove the file you created as it contains sensitive information about your PHP environment and your Ubuntu server. Use rm to do so:

sudo rm /var/www/your_domain/info.php        

You can always recreate this page if you need to access the information again later.


要查看或添加评论,请登录

Syed Bilal Ali的更多文章

  • Building My First Shopify Custom App Using Remix

    Building My First Shopify Custom App Using Remix

    As a developer, we often encounter projects that challenge us, push our boundaries, and ultimately help us grow…

    4 条评论
  • A Comprehensive Guide on Integrating Firebase with Nest JS

    A Comprehensive Guide on Integrating Firebase with Nest JS

    Nest JS has become a popular backend framework. However, there is a lack of good articles or guides on how to integrate…

    4 条评论
  • Vite VS Webpack Mix

    Vite VS Webpack Mix

    Laravel Mix and Laravel Vite are the two options available to developers for front-end development in the framework…

  • Payment Process with Terminal Transaction

    Payment Process with Terminal Transaction

    Recently, I had the opportunity to dive deep into the world of Wallee Payment Gateway integration, and let me tell you,…

    3 条评论
  • Remove Image Background using NodeJS

    Remove Image Background using NodeJS

    Introduction: In today's digital world, images play a crucial role in various applications, from e-commerce websites to…

    2 条评论
  • NestJS unit testing

    NestJS unit testing

    This tutorial is a deep dive into unit testing in NestJS (including mocking with test doubles). To get the most out of…

    1 条评论
  • Pseudo-Palindromic Paths in a Binary Tree

    Pseudo-Palindromic Paths in a Binary Tree

    Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be…

  • JQuery ContextMenu plugin

    JQuery ContextMenu plugin

    Designed for web applications that require menus on a potentially huge number of items, the contextMenu Plugin In…

  • Building a Scalable Microservice Architecture for Nest.js Projects

    Building a Scalable Microservice Architecture for Nest.js Projects

    1. Introduction to Microservices 2.

  • Implementing Socket.IO in NestJS using webSockets

    Implementing Socket.IO in NestJS using webSockets

    Install the required dependencies: Create a new module for Socket.IO in NestJS: Inside the module, create a new service…

    1 条评论

社区洞察

其他会员也浏览了