Install, Configure and Secure Magento on Ubuntu & CentOS

Posted on

Install, Configure and Secure Magento on Ubuntu & CentOS

Install, Configure and Secure Magento on Ubuntu & CentOS

Magento is a robust, open-source e-commerce platform crafted in PHP, offering a versatile shopping cart system and comprehensive control over the visual appeal, content, and functionality of your online store. Its adaptability allows for installation on a variety of Linux distributions, including Ubuntu, Debian, CentOS, and Red Hat.

This comprehensive guide details the process of installing, configuring, and securing Magento 2 on Ubuntu 18.04/20.4/22.04 and CentOS 7/8 from the ground up, ensuring a stable and secure foundation for your online business. The title, "Install, Configure and Secure Magento on Ubuntu & CentOS," reflects the core purpose of this guide.

Prerequisites

Before embarking on the installation process, verify that your server meets the following minimum requirements:

  • Operating System: Ubuntu 18.04/20.04/22.04 or CentOS 7/8
  • Web Server: Apache 2.2 or later, or Nginx 1.x
  • PHP: 7.3 or later (Magento 2.4 and above requires PHP 7.4 or 8.1)
  • MySQL: 5.6 or later
  • RAM: Minimum 2GB (4GB or more recommended)
  • Composer: Latest version

Also, ensure your firewall permits HTTP (port 80) and HTTPS (port 443) traffic if it is enabled on the server.

Step 1 – Install LAMP Stack (Linux, Apache, MySQL, PHP)

Magento necessitates a LAMP (Linux, Apache, MySQL, PHP) or LEMP (Linux, Nginx, MySQL, PHP) stack for optimal performance. Here’s how to install Apache, MySQL, and PHP on Ubuntu:

# Install Apache
$ sudo apt update
$ sudo apt install apache2

# Install MySQL
$ sudo apt install mysql-server

# Secure MySQL installation
$ sudo mysql_secure_installation

# Install required PHP packages
$ sudo apt install php php-cli php-mysql php-gd php-curl php-bcmath php-mbstring php-xml php-zip

# Restart Apache
$ sudo systemctl restart apache2

For CentOS 7, the LAMP stack can be installed using these commands:

# Install Apache
$ sudo yum install httpd

# Start Apache
$ sudo systemctl start httpd
$ sudo systemctl enable httpd

# Install MySQL
$ sudo yum install mysql-server

# Secure MySQL installation
$ sudo mysql_secure_installation

# Install EPEL repository
$ sudo yum install epel-release yum-utils

# Install Remi's RPM repository
$ sudo yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm

# Enable PHP 7.4 Remi repo (or desired version)
$ sudo yum-config-manager --enable remi-php74

# Install PHP
$ sudo yum install php php-cli php-mysqlnd php-opcache php-gd php-curl php-mcrypt php-xml php-mbstring

# Restart Apache
$ sudo systemctl restart httpd

These commands install a basic LAMP stack on both operating systems, defaulting to PHP 7.3 on CentOS 7 unless otherwise configured.

Step 2 – Install Composer

Composer is a PHP dependency manager crucial for installing Magento and its dependencies. Installation steps:

# Download and install Composer
$ curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

Verify the installation:

$ composer --version

Step 3 – Download and Install Magento

With the environment set up, you’re ready to install Magento 2 using Composer.

Create the document root directory:

$ sudo mkdir -p /var/www/html/magento2

Navigate to the document root:

$ cd /var/www/html/magento2

Run Composer to install Magento:

$ composer create-project --repository-url=https://repo.magento.com/ magento/project-community-edition .

This downloads and installs the latest Magento 2 Community Edition in the current directory.

Step 4 – Set Up Database for Magento

Magento needs a database to store its information. Create a new database and user specifically for Magento.

Log in to the MySQL shell:

$ sudo mysql -u root -p

Create a new database:

CREATE DATABASE magento;

Create a new user and grant privileges:

CREATE USER 'magento'@'localhost' IDENTIFIED BY 'strong_password';
GRANT ALL PRIVILEGES ON magento.* TO 'magento'@'localhost';

Flush privileges and exit:

FLUSH PRIVILEGES;
exit

Remember to replace strong_password with a secure password.

Step 5 – Configure Magento

Configure Magento to use the newly created database.

Rename the default config file:

$ mv app/etc/env.php app/etc/env.php.bak

Edit app/etc/env.php :

$ sudo nano app/etc/env.php

Update the file with your database credentials:

return [
    'db' => [
        'table_prefix' => '',
        'connection' => [
            'default' => [
                'host' => 'localhost',
                'dbname' => 'magento',
                'username' => 'magento',
                'password' => 'strong_password',
                'model' => 'mysql4',
                'engine' => 'innodb',
                'initStatements' => 'SET NAMES utf8;',
                'active' => '1',
            ]
        ]
    ],
];

Save and close the file after updating the credentials.

Step 6 – Set Up Ownership and Permissions

For security, the Magento files should be owned by the web server user and have appropriate permissions.

Determine your web server user:

$ ps aux | grep apache

On Ubuntu, it’s typically www-data. On CentOS, it’s apache.

Set ownership:

$ sudo chown -R www-data:www-data /var/www/html/magento2

Set recursive permissions:

$ sudo find /var/www/html/magento2 -type f -exec chmod 644 {} ;
$ sudo find /var/www/html/magento2 -type d -exec chmod 755 {} ;
$ sudo chmod o+w /var/www/html/magento2/var
$ sudo chmod o+w /var/www/html/magento2/pub/media
$ sudo chmod o+w /var/www/html/magento2/pub/static

This restricts permissions and provides the web server user with the necessary read/write access.

Step 7 – Install Magento

Complete the installation through the web interface.

Navigate to http://your_server_ip/magento2 in your browser. The setup wizard will guide you through the remaining steps.

Step 8 – Configure Base URL

Set the base URL for your Magento 2 installation for proper functionality.

Access the Magento admin dashboard at http://your_server_ip/magento2/admin and log in.

Go to Stores > Configuration > General > Web.

Set Base URLs to your domain name (e.g., example.com/magento2). Click Save Config.

This ensures assets and links function correctly.

Step 9 – Setup Cron Jobs

Magento requires background cron jobs for scheduled tasks like sending emails, indexing, and cleanup.

Set up cron for Magento:

$ crontab -e

Add the following lines:

* * * * * /usr/bin/php /var/www/html/magento2/bin/magento cron:run | grep -v "Ran jobs by schedule" >> /var/www/html/magento2/var/log/magento.cron.log
* * * * * /usr/bin/php /var/www/html/magento2/update/cron.php >> /var/www/html/magento2/var/log/update.cron.log
* * * * * /usr/bin/php /var/www/html/magento2/bin/magento setup:cron:run >> /var/www/html/magento2/var/log/setup.cron.log

These entries run the Magento cron job, update cron job, and setup cron job, logging their output.

Step 10 – Secure Magento

Magento, while flexible, can be vulnerable to exploits in its default configuration. Here are some steps to enhance the security of your Magento 2 store.

Use HTTPS

Implement HTTPS on your server with a valid SSL certificate. All traffic, including admin access, should use HTTPS to encrypt communication and prevent eavesdropping.

Strong Admin Credentials

Change the default admin username and use a strong, unique password. Enable two-factor authentication for added security.

Limit Admin Path

Modify the default /admin path to something less predictable, like /secret-admin-access.

Disable File Execution

Prevent the execution of PHP files in directories like app, lib, dev, var, and generated. This can be accomplished through Apache or Nginx configuration. For Apache, you can use .htaccess files:

<Directory /var/www/html/magento2/app>
    <Files "*.php">
        Order Deny,Allow
        Deny from all
    </Files>
</Directory>

# Repeat for other directories (lib, dev, var, generated)

Restrict Permissions

Adhere to the principle of least privilege. Set restrictive permissions for web-accessible files and folders, limiting write access to only necessary directories like media, var, and generated.

Monitor for Suspicious Activity

Regularly review logs for unauthorized or unusual activity, such as failed login attempts, file changes, or PHP execution in restricted directories.

Keep Software Up-to-Date

Install security patches and feature updates promptly to address known vulnerabilities.

Add Security Extensions

Consider using extensions like Magento Security Scan or Magento Malware Scanner to provide additional protection and monitoring.

Use a Web Application Firewall (WAF)

A WAF can identify and block common web exploits like XSS, SQL injection, and RFI, providing an extra layer of security.

By implementing these security measures, you can create a more secure Magento 2 environment, protecting your data and your customers. The topic of "Install, Configure and Secure Magento on Ubuntu & CentOS" is central to this guide.

Alternative Solutions

While the above guide provides a solid foundation for setting up Magento, here are two alternative approaches to consider:

1. Using Docker Containers:

Instead of directly installing the LAMP stack on the host operating system, Docker containers offer a more isolated and reproducible environment. This approach simplifies dependency management, avoids conflicts between different PHP versions or libraries, and makes deployment more consistent across different environments.

  • Explanation: Docker allows you to package Magento and all its dependencies (Apache/Nginx, PHP, MySQL/MariaDB) into containers. These containers are self-contained and run in isolation from the host system, ensuring that changes to the host system don’t affect the Magento installation and vice versa.

  • Code Example (Docker Compose): A docker-compose.yml file can define the services required for Magento:

version: "3.8"
services:
  db:
    image: mariadb:10.6
    environment:
      MYSQL_ROOT_PASSWORD: root_password
      MYSQL_DATABASE: magento
      MYSQL_USER: magento
      MYSQL_PASSWORD: magento_password
    volumes:
      - db_data:/var/lib/mysql

  web:
    image: php:8.1-apache
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./magento:/var/www/html
    environment:
      PHP_MEMORY_LIMIT: 2G
    depends_on:
      - db

volumes:
  db_data:

This example defines two services: db (MariaDB) and web (PHP with Apache). You would place your Magento code in the ./magento directory. This approach greatly simplifies "Install, Configure and Secure Magento on Ubuntu & CentOS."

2. Using a Managed Magento Hosting Provider:

Rather than self-managing the entire infrastructure, using a managed Magento hosting provider offloads the responsibility of server setup, security, and maintenance to experts. This allows you to focus solely on developing and growing your online store.

  • Explanation: Managed Magento hosting providers typically offer optimized server configurations, automatic updates, security patches, and dedicated support. They handle the complexities of server management, ensuring high performance and security for your Magento store. Examples include Cloudways, Nexcess, and MageMojo.

  • Benefits:

    • Reduced operational overhead.
    • Improved performance and scalability.
    • Enhanced security.
    • Expert support.

While this doesn’t involve code, the provider manages the entire infrastructure, taking care of the "Install, Configure and Secure Magento on Ubuntu & CentOS" aspects.

Conclusion

Magento is a powerful e-commerce platform that allows merchants to create highly customized online stores. This guide has provided a detailed walkthrough on how to install, configure, and secure Magento 2 on Ubuntu and CentOS for production environments.

Key takeaways:

  • Ensure your server meets the minimum requirements.
  • Follow the installation steps carefully, including setting up the database and file permissions.
  • Implement security best practices to protect your store from vulnerabilities.
  • Consider alternative solutions like Docker or managed hosting to simplify deployment and maintenance.

By following these steps, you can deploy Magento securely and leverage its extensive features to build a thriving online business. This guide is the beginning to a long process, but following the correct steps will ensure the store is secure. This article details the "Install, Configure and Secure Magento on Ubuntu & CentOS" process.

Leave a Reply

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