ApacheMagento 2Ubuntu 18.04Ubuntu 20.04Ubuntu 20.10

How to Install Magento 2.4 with Apache on Ubuntu 20.04

9 Mins read
  • Step by Step Guide to Install Magento 2.4.1 with Apache on Ubuntu 20.04, Ubuntu 18.04, Ubuntu 22.10 and Ubuntu 22.04 using Composer 2 and Command line ( CLI )

Install & Configure Apache

First of all, update your Ubuntu 20.04 system packages and install apache 2 using following commands in CLI.

sudo apt update
sudo apt install apache2

Once the installation is finished, you’ll need to adjust your firewall settings to allow HTTP and HTTPS traffic.

To list all currently available UFW application profiles, you can run:

sudo ufw app list
sudo ufw allow in "Apache Full"
sudo ufw delete allow 'Apache'
  • Apache Full: This profile opens both port 80 (normal, unencrypted web traffic) and port 443 (TLS/SSL encrypted traffic).

You can verify the change with:

sudo ufw status

Now open your domain in browser and you will see the default Ubuntu 20.04 Nginx web page. It should look something like this:

For localhost: http://localhost

If you see this page, then your web server is now correctly installed and accessible through your firewall.

Verify that the apache2 service is active/running and is enabled to automatically start at system startup using the following systemctl commands

sudo systemctl is-active apache2
sudo systemctl is-enabled apache2
sudo systemctl status apache2

Install MySQL

Install MySQL 8 using apt command

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.

sudo mysql_secure_installation

Answer Y for yes

Select a level of password validation

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:

For the rest of the questions, press Y and hit the ENTER key at each prompt.

When you’re finished, test if 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. You should see output like this:

To exit the MySQL console, type:

exit

Your MySQL server is now installed and secured. Next, we’ll install PHP.

Install PHP

Install PHP 7.4 and other Packages with below command.

sudo apt install php7.4 libapache2-mod-php php-mysql

Verify installed PHP version

php -v

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
<IfModule mod_dir.c>
        DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>

Enable the mbstring PHP extension

sudo apt install php7.4-mbstring
sudo phpenmod mbstring

Reload Apache so the changes take effect:

sudo systemctl reload apache2

Install phpMyAdmin (Optional)

Login to mysql

sudo mysql

Or, if you enabled password authentication for the root MySQL user,

mysql -u root -p

Disable the Validate Password component.

UNINSTALL COMPONENT "file://component_validate_password";
exit

Note: that this won’t actually uninstall it, but just stop the component from being loaded on your MySQL server:

 Install phpmyadmin 

sudo apt install phpmyadmin php-zip php-gd php-json php-curl
  • For the server selection, choose apache2 ( hit space and select first and then hit enter otherwise it will just look highlighted with red color but it will not be selected.)
  • 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

Select TCP/IP Connection Method

Once phpMyAdmin is installed, re-enable the Validate Password component:

sudo mysql

Or, if you enabled password authentication for the root MySQL user,

mysql -u root -p
INSTALL COMPONENT "file://component_validate_password";
exit

Reload Apache so the changes take effect:

sudo systemctl restart apache2

Configure Password Access for the MySQL Root Account

sudo mysql

Or, if you enabled password authentication for the root MySQL user,

mysql -u root -p
SELECT user,authentication_string,plugin,host FROM mysql.user;

Make sure to replace your_secure_password with your password.

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_secure_password';
SELECT user,authentication_string,plugin,host FROM mysql.user;
exit

Create new MySQL User for magento 2 & Configure Password Access

Here you can choose more secure name for your user. But for this tutorial I will create magento user.

sudo mysql

Or, if you enabled password authentication for the root MySQL user,

mysql -u root -p
SELECT user,authentication_string,plugin,host FROM mysql.user;

Make sure to replace your_secure_password with your password.

CREATE USER 'magento2'@'localhost' IDENTIFIED BY 'your_secure_password';
ALTER USER 'magento2'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_secure_password';
GRANT ALL PRIVILEGES ON *.* TO 'magento2'@'localhost' WITH GRANT OPTION;
SELECT user,authentication_string,plugin,host FROM mysql.user;
exit

Now you can verify phpmyadmin whether it is accessible or not.

https://your-domain/phpmyadmin

For localhost : http://localhost/phpmyadmin

Now here if you are not able to see phpmyadmin page and if you are getting 404 Page not found error on the PHPMyAdmin link, you can fix it with the below commands.

How to Fix 404 Page not found error on the PHPMyAdmin Ubuntu 20.04
sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-available/phpmyadmin.conf
sudo a2enconf phpmyadmin
sudo systemctl restart apache2

Secure Your phpMyAdmin with .htpasswd

It is not advisable to keep phpmyadmin page open for public. You can create username and password for that page to add and extra layer of security.

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

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

Add an AllowOverride All directive

Relstart Apache so the changes take effect:

sudo systemctl restart apache2

Create .htaccess file and add below code in that file

sudo nano /usr/share/phpmyadmin/.htaccess

/usr/share/phpmyadmin/.htaccess

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

Create username and password to access phpmyadmin page.

sudo htpasswd -c /etc/phpmyadmin/.htpasswd secure_username

If you want to enter an additional user,

sudo htpasswd /etc/phpmyadmin/.htpasswd another_secure_username

Verify the PHPMyAdmin page, it must ask username and password. Once you enter the correct username and password it will redirect and allow you to access the PHPMyAdmin page.

https://your-domain/phpmyadmin

For Localhost: http://localhost/phpmyadmin

Set Up Let’s Encrypt SSL Certificate with Auto-Renewal Cron (Optional)

Install Certbot

sudo apt install certbot python3-certbot-apache
sudo apache2ctl configtest
sudo systemctl reload apache2

Obtain SSL Certificates

sudo certbot --apache

Select your domain in next step and after that complete other steps in process.

Verify Certbot Auto-Renewal

sudo systemctl status certbot.timer

To test the renewal process, you can do a dry run with certbot:

sudo certbot renew --dry-run

Open /etc/apache2/sites-available/your-domain-le-ssl.conf or your virtual host file for SSL ( 443 port ) if you haven’t configure SSL with Let’s Encrypt.

Set AllowEncodedSlashes in the server config (globally) or in the virtual host configurations to avoid decoding the encoded slashes that may cause issues for URLs. For instance, when retrieving products with a slash in the SKU via the API, you will not want that converted.

<VirtualHost *:443>
  ...
  # Allow encoded slashes
  AllowEncodedSlashes NoDecode
  ...
</VirtualHost>

Install & configure Apache modules for Magento 2

Enable the Apache rewrite module

sudo a2enmod rewrite
sudo apt install php7.4-bcmath php7.4-intl php7.4-soap

Install Elastic Search

Install OpenJDK 11

sudo apt install openjdk-11-jdk

Once the installation is complete, verify java version with below command.

java -version

Install Elasticsearch

curl -fsSL https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -

After that, add the Elastic source list to the sources.list.d director

echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" | sudo tee -a /etc/apt/sources.list.d/elastic-7.x.list
sudo apt update
sudo apt install elasticsearch
Install Elastic Search with below command in Ubuntu 20.04
Install Elastic Search with below command in Ubuntu 20.04

Configure Elasticsearch on Ubuntu 20.04

sudo a2enmod proxy && sudo a2enmod proxy_http && sudo service apache2 restart

Create new virtual host file for Elasticsearch proxy

sudo nano /etc/apache2/ports.conf

Add Listen 8080

Allow Apache to Listen 8080 port
Allow Apache to Listen 8080 port

open /etc/apache2/sites-available/your-domain-elasticsearch.conf

sudo nano /etc/apache2/sites-available/your-domain-elasticsearch.conf
<VirtualHost *:8080>
    ProxyPass "/" "http://localhost:9200/"
    ProxyPassReverse "/" "http://localhost:9200/"
</VirtualHost>
sudo a2ensite your-domain-elasticsearch
sudo service apache2 restart

Start the Elasticsearch service with systemctl & enable Elasticsearch to start up every time your server boots.

sudo systemctl start elasticsearch
sudo systemctl enable elasticsearch
Enable Elasticsearch to start up every time your server boots
Enable Elasticsearch to start up every time your server boots

Verify Elasticsearch proxy is working or not ?

curl -i http://localhost:8080/_cluster/health
Verify Elasticsearch proxy is working or not
Verify Elasticsearch proxy is working or not

If should return the output as above.

Install Redis (Optional)

sudo apt install redis-server

Open up the Redis configuration file 

sudo nano /etc/redis/redis.conf

Inside the file, find the supervised directive which allows you to declare an init system and change its value from no to systemd:

Change supervised directive value from no to systemd
Change supervised directive value from no to systemd

why ? because you are running Ubuntu, which uses the systemd init system.

Configure Redis Password

sudo nano /etc/redis/redis.conf

Scroll to the SECURITY section and look for a commented directive requirepass

Remove #, and change foobared to a secure password: ( Line No: 507 )

Remove and change foobared to a secure password
Remove and change foobared to a secure password

After setting the password, save and close the file, then restart Redis

sudo systemctl restart redis.service

Check Redis is working or not with below command ?

sudo systemctl status redis
Check Redis is working or not
Check Redis is working or not

Install Composer 2

Downloading and Installing Composer 2

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

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 composer-setup.php --install-dir=/usr/local/bin --filename=composer --version=1.10.16

Check Composer 2 is installed or not in Ubuntu?

composer
Steps to Install Composer on Ubuntu 20.04
Steps to Install Composer on Ubuntu 20.04

Great! Finally we are ready to install Magento 2.4

Get your authentication keys

Get Authentication Keys To Install Magento 2 on Ubuntu 20.04
Get Authentication Keys To Install Magento 2.4.1 on Ubuntu 20.04
  • Click on Create A New Access Key Button
  • Enter a key name and generate

Get the Magento 2.4.x metapackage

  • Go to root folder and execute below command to change permission.
cd /var/www/html
sudo chown -R $USER:$USER /var/www/html
  • Create a new Composer project using the Magento Open Source or Magento Commerce metapackage on magento2 directory. If you want you can change the directory name as per your requirement in the below command.
composer create-project --repository-url=https://repo.magento.com/ magento/project-community-edition magento2
Install Magento 2.4.x on Ubuntu 20.04 1
Install Magento 2.4.1 on Ubuntu 20.04

Set Up Virtual Hosts

Create Virtual Host Config file

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

Update /etc/apache2/sites-available/your_domain.conf file as below and make sure to change your-domain with your actual domain name

<VirtualHost *:80>
    ServerName your-domain
    ServerAlias www.your-domain 
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/magento2

    <Directory /var/www/html/magento2/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>


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

Activate Your Virtual Host Configuration file and deactivate 000-default host conf file to avoid conflict.

sudo a2ensite your_domain
sudo a2dissite 000-default

Reload Apache so the changes take effect:

sudo systemctl reload apache2

Update Directory & File Permissions for Magento 2.4.x

Set read-write permissions so that command line can write files to the Magento 2 file system.

cd /var/www/html/magento2
find var generated vendor pub/static pub/media app/etc -type f -exec chmod g+w {} +
find var generated vendor pub/static pub/media app/etc -type d -exec chmod g+ws {} +
sudo chown -R :www-data . 
sudo chmod u+x bin/magento

Install Magento 2.4.1

At the time of writing, current version of magento is 2.4.1. So we will install Magento 2.4.1 on Ubuntu 20.04 LTS.

This tutorial assumes that:

  • Domain name is http://localhost
  • Domain Root Directory is /var/www/html/magento2
  • Database Host is on the same machine (localhost)
  • Database Name is magento2
  • Database User is magento2
  • Database Password is admin

So please make sure to update those values as per your requirement.

Go to Domain root Directory:

cd /var/www/html/magento2

Execute below command:

bin/magento setup:install \
--base-url=http://localhost \
--db-host=localhost \
--db-name=magento2 \
--db-user=magento2 \
--db-password=admin \
--admin-firstname=Admin \
--admin-lastname=Admin \
--admin-email=admin@admin.com \
--admin-user=admin \
--admin-password=admin123 \
--language=en_US \
--currency=USD \
--timezone=America/Chicago \
--use-rewrites=1

Once you will execute above command it should successfully install Magento 2.4.1

Install Magento 2.4.1 on Ubuntu 20.04
Install Magento 2.4.1 on Ubuntu 20.04

Setup Google Authenticator for Two Factor Authentication

Below are the steps to Setup 2FA or Fix Two Factor Authentication issue with initial installation of Magento 2.4.1

  • Select Google Authenticator as the 2FA provider:
bin/magento config:set twofactorauth/general/force_providers google
  • Increase the lifetime of the window to 60 seconds to prevent tokens from expiring.
bin/magento config:set twofactorauth/google/otp_window 60
  • Generate a Base32-encoded string for the shared secret value

For example, encoding the string secretkey1 with the online [Base32 Encode][13] tool ( https://cryptii.com/pipes/base32 ) returns the value ONSWG4TFORVWK6JR.

Please make sure to change ONSWG4TFORVWK6JR string as per your secret key in below commands

  • Add the encoded shared secret to Google Authenticator.
bin/magento security:tfa:google:set-secret admin ONSWG4TFORVWK6JR
Setup Google Authenticator for Two Factor Authentication in Magento 2 1
Setup Google Authenticator for Two Factor Authentication in Magento 2 1
  • Open Google Authenticator Application on your mobile and Add new Key ONSWG4TFORVWK6JR
  • Once you will add Your key you will see Authenticator code in application. Copy that Authenticator code and use it to login in magento 2 admin panel.
two factor authentication in magento 2.4
two factor authentication in magento 2.4
Screenshot 8
Magento 2 Admin Panel
Magento 2 Front End
Magento 2 Front End

Disable Magento_TwoFactorAuth Module in Magento 2.4

Two Factor Authentication issue in Magento 2.4.1
Two Factor Authentication issue in Magento 2.4.1

If you are installing magento2 on local system or want a quick access you can execute below command to disable Magento_TwoFactorAuth module in magento 2.4.1

sudo bin/magento module:disable Magento_TwoFactorAuth
Disable Two Factor Authentication in Magento 2.4
Disable Two Factor Authentication in Magento 2.4

If you want to enable Magento_TwoFactorAuth module you can use below command

sudo bin/magento module:enable Magento_TwoFactorAuth

I hope you are able to install Magento 2.4 with this guide. Please let me know in the comment below if you are facing any issue in installation with this guide.

Related posts
Magento 2NGINXUbuntu 18.04

Install Magento 2.4 in Ubuntu 18.04 with NGINX

8 Mins read
Magento 2NGINXUbuntu 20.04

Install Magento 2.4 in Ubuntu 20.04 with NGINX

8 Mins read
Composer 2Ubuntu 18.04Ubuntu 20.04Ubuntu 20.10

How to Update or Upgrade Composer Version in Ubuntu

1 Mins read
Join our bi-weekly newsletter to stay informed!

4 Comments

Leave a Reply

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