Celebrate Our 22nd Anniversary with Huge Savings! Up to 70% Off

How to Optimize Magento for Speed on Your Ubuntu VPS?

A slow-loading Magento store not only drives visitors away but can also hurt your search engine rankings and conversion rates. If you're hosting your Magento site on an Ubuntu VPS, you have full control of your environment, which opens the door to powerful performance optimizations.

In this guide, we’ll cover the best practices for both Apache (LAMP) and Nginx (LEMP) setups, along with caching strategies, database optimizations, and image enhancements to boost your Magento store’s speed and efficiency.

 

Prerequisites

  • A VPS with Ubuntu installed
  • Magento 2 is installed and running
  • SSH access to your VPS
  • Sudo privileges or root access
 

1. Steps for Apache or Nginx Setup

Optimizing your web server is the first step to improving Magento's performance on your VPS. Magento can run on both Apache and Nginx, each with its own strengths. Understanding these differences and configuring them correctly is crucial. Read this article to know the difference between Apache and Nginx.

 

Apache (LAMP Stack):

Apache is the traditional choice for Magento hosting, offering extensive documentation and support. To enhance its performance, you can optimize Apache modules and configuration.

 

Key Optimization:

  • Enable mod_expires and mod_deflate to control caching and compression of static files.
  • Configure KeepAlive settings to improve persistent connections.
 
Want to set up Apache on your server? Here’s a quick guide to installing the LAMP stack on Ubuntu 20.04.
 

Nginx (LEMP Stack):

Nginx is known for its lightweight, high-performance nature, especially for handling large traffic loads. It is a non-blocking web server, ideal for serving static files faster.

 

Key Optimization:

  • Use PHP-FPM to process PHP requests efficiently.
  • Enable gzip compression like mod_deflate in Apache, this shrinks file sizes for faster page loads.
     
    Want to set up Nginx on your server? Here’s a quick guide to installing the LEMP stack on Ubuntu 20.04.
     

    Note: This article covers all the steps for Nginx.

    Magento is built using PHP, so it needs PHP to work. When using Nginx, the best way to handle these PHP requests is by using PHP-FPM (which stands for FastCGI Process Manager). PHP-FPM helps Nginx process PHP code efficiently and keeps your site running well under heavy traffic.

1. Check your PHP version:

 
PHP -v

 

2. Make sure PHP-FPM is installed for the version you're using. For example, if you're using PHP 8.2 (as shown in the output), install PHP-FPM with:

 
sudo apt install php8.2-fpm

 
Note: Before making changes, it's wise to back up your current Nginx site configuration:
 

3. Open your Nginx site config file:

 
 

sudo nano /etc/nginx/sites-available/default

 

You will see the code like in the screenshot; delete all the code with CTRL + K.

Note: The default Nginx configuration file is meant for basic websites and doesn't support PHP or Magento. If you leave that code in place, it can conflict with the Magento-specific settings and prevent your store from working properly.

To avoid issues and ensure Magento runs well, it's best to remove all the existing code and replace it with a clean configuration that is optimized for PHP-FPM and Magento.

 
 

 

The following Nginx configuration is optimized for Magento to efficiently handle PHP requests through PHP-FPM and to serve static content.

Replace php8.2-fpm.sock with the correct path for your PHP version's FPM socket.

You can usually find this in your PHP-FPM configuration files (e.g., /etc/php/8.2/fpm/pool.d/www.conf).

And now you paste the below code

Replace php8.2-fpm.sock with your correct PHP version if different.

 
 

server {

    listen 80 default_server;

    listen [::]:80 default_server;

    root /var/www/html;

    index index.php index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {

        try_files $uri $uri/ =404;

    }

    location ~ \.php$ {

        include snippets/fastcgi-php.conf;

        fastcgi_pass unix:/run/php/php8.2-fpm.sock;

    }

    # deny access to .htaccess files, if Apache's document root

    # concurs with nginx's one

    #

    #location ~ /\.ht {

    #    deny all;

    #}

}

 

To save this, Press Ctrl + O

Press Enter

Then, Press Ctrl + X

4. Test configuration:

 
sudo nginx -t

 

2. PHP OPcache: Speed Up PHP Execution

Both Nginx and Apache setups can benefit from enabling PHP OPcache to reduce server load and improve execution time. helps by “remembering” the compiled version of this PHP code, so your server doesn’t have to reprocess it every time.

How to Enable:

Edit php.ini and set opcache.enable=1 and opcache.memory_consumption=128.

1. Locate the php.ini file

Open the PHP configuration file using a text editor. For PHP 8.2 (CLI), run:

 
 

sudo nano /etc/php/8.2/cli/php.ini

 

2. Find the following lines in the file and make the changes:

In a PHP configuration file (php.ini), any line that starts with a semicolon is treated as a comment, meaning it is ignored by PHP, so we remove the semicolon in the below steps.

Change:

 
;opcache.enable=1

 

To:

 
opcache.enable=1

 

And update:

 
;opcache.memory_consumption=128

 

To:

 
opcache.memory_consumption=128

 

3. Press CTRL + O to save

4. Press ENTER to confirm

5. Press CTRL + X to exit the editor

6. Restart PHP-FPM and Nginx

Run the following commands to apply the changes:

 
 

sudo systemctl restart php8.2-fpm

 
 

sudo systemctl restart nginx

 

7. Confirm OPcache is Enabled

Create a test file:

 
 

sudo nano /var/www/html/info.php

 

Paste the following:

 
<?php phpinfo(); ?>

 

Save and access it from the browser:

http://your-server-ip/info.php

Search for "OPcache" and check if it's enabled.

 
 

 

3. Database Optimization for Magento

A well-configured database is essential for Magento’s performance.

Magento stores a lot of information in a database, like product details, customer info, and orders. If the database isn’t set up well, it can slow down your entire site.

In most Magento setups, the database is MySQL or MariaDB. They're very similar, and both work well with Magento.

  • Magento uses a database engine called InnoDB. To make it faster, we increase the buffer pool, which is memory the database uses to keep frequently accessed data ready.
  • Optimize query_cache_size for faster queries.
 
Note: The query cache was removed in MySQL 8.0 and later versions.
 

1. Increase innodb_buffer_pool_size

This allows MySQL to keep more data in memory, reducing disk I/O and speeding up queries.

 
 

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

 

Under the [mysqld] section, add or update:

 
innodb_buffer_pool_size = 256M

 

Note: Adjust 512M depending on your server's RAM:

If you have 1 GB RAM → use 256M

If 2 GB+ RAM → use 512M or more (up to ~70% of RAM)

 

2. Verify It’s Applied

 
 

mysql -u root -p

 

You'll be prompted with:

Enter password:

Type the MySQL root password and press Enter.

3. Then you can run:

 
SHOW VARIABLES LIKE 'innodb_buffer_pool_size';

 

4. Caching Mechanisms for Faster Load Times

Caching is crucial for enhancing the speed and responsiveness of your Magento store. By storing frequently accessed data in memory, you can significantly reduce the load on your server and deliver content to users much faster.

Redis: Redis is a powerful caching solution for both setups. Use Redis to cache data and session storage, significantly improving page load times.

How to Set Up Redis:

1. Install Redis:

 
 

sudo apt install redis-server

 

2. Enable and Start Redis:

 
 

sudo systemctl enable redis-server

 
 

sudo systemctl start redis-server

 

3. Verify Redis is Running:

 
sudo systemctl status redis-server

 

4. Now run this command to confirm it's responsive:

 
 

redis-cli ping

 

5. If it returns:

 
PONG

 

6. Connect Redis to Magento

 

sudo nano /var/www/html/app/etc/env.php

7. Edit the env.php file (typically located at /var/www/html/app/etc/env.php):

Add or modify these entries:

 
 

'session' => [

    'save' => 'redis',

    'redis' => [

        'host' => '127.0.0.1',

        'port' => '6379',

        'timeout' => '2.5',

        'persistent_identifier' => '',

        'database' => '2',

        'compression_threshold' => '2048',

        'compression_library' => 'gzip',

        'log_level' => '1',

        'max_concurrency' => '6',

        'break_after_frontend' => '5',

        'break_after_adminhtml' => '30',

        'first_lifetime' => '600',

        'bot_first_lifetime' => '60',

        'bot_lifetime' => '7200',

        'disable_locking' => '0',

        'min_lifetime' => '60',

        'max_lifetime' => '2592000'

    ]

],

'cache' => [

    'frontend' => [

        'default' => [

            'backend' => 'Cm_Cache_Backend_Redis',

            'backend_options' => [

                'server' => '127.0.0.1',

                'port' => '6379',

                'database' => '0',

                'compress_data' => '1'

            ]

        ],

        'page_cache' => [

            'backend' => 'Cm_Cache_Backend_Redis',

            'backend_options' => [

                'server' => '127.0.0.1',

                'port' => '6379',

                'database' => '1',

                'compress_data' => '0'

            ]

        ]

    ]

]

 

8. Flush Magento Cache:

 
 

php bin/magento cache:flush

 
  • Varnish: Varnish is a powerful HTTP accelerator. Configure Varnish as a reverse proxy for full-page caching, reducing the load on your server.
  • Varnish Configuration: This is ideal for both Nginx and Apache, though the configuration differs slightly. Ensure the proper connection between Varnish and your backend server (either Nginx or Apache).
 

5. Magento Production Mode for Optimal Performance

  • Switch Magento to Production Mode to disable unnecessary logging and enable advanced caching mechanisms.

    How to Set Production Mode:

    Run the following Magento CLI command:

     
     

    php bin/magento deploy:mode:set production

     
 

6. Optimizing Static Content Delivery

Static files like CSS, JavaScript, and images can slow down your website if they aren’t optimized.

  • CSS and JS Minification: Magento has built-in options for merging and minifying JavaScript and CSS files to reduce the number of HTTP requests.
  • CDN (Content Delivery Network): Use a CDN to serve static assets, decreasing load times by caching files closer to the user.
 

7. Image Optimization for Faster Loading

Images account for a significant portion of a page's load time. Optimize your images using tools like ImageMagick or online services like TinyPNG. You can also convert images to the WebP format for faster loading and better quality.

1. Magento supports ImageMagick for image processing. First, ensure it's installed:

 
 

sudo apt update

 
 

sudo apt install imagemagick php-imagick -y

 

2. Then restart your web server:

If you're using Apache, run:

 
 

sudo systemctl restart apache2

 

If you're using Nginx, run:

 
 

sudo systemctl restart nginx

 

3. Check if ImageMagick is installed by running

 
convert -version

 

4. Navigate to Magento Product Image Folder

 
 

cd /var/www/html/magento2/pub/media/catalog/product

 

5. Back Up Images (Optional but Recommended)

 
 

mkdir -p /var/www/html/magento2/pub/media/catalog/product_backup

 
 

cp -r . /var/www/html/magento2/pub/media/catalog/product_backup

 

6. Compress Images Using ImageMagick

For .jpg files:

 
 

find . -type f -iname "*.jpg" -exec mogrify -strip -interlace Plane -gaussian-blur 0.05 -quality 85% {} \;

 

For .png files:

 
 

find . -type f -iname "*.png" -exec mogrify -strip -quality 85 {} \;

 

7. Convert to WebP Format (Keep Originals)

 
 

find . -type f \( -iname "*.jpg" -o -iname "*.png" \) -exec bash -c 'cwebp "$0" -q 80 -o "${0%.*}.webp"' {} \;

 

8. Configure Cron Jobs for Maintenance

Magento relies on cron jobs to automate tasks like indexing, sending emails, and cleaning up logs. Ensure these jobs run as scheduled to avoid performance degradation.

How to Set Up Cron Jobs: Use the Magento CLI to configure cron tasks:

1. Navigate to your Magento root directory via SSH.

 
 

cd /path/to/your/magento/root

 

2. Run the Magento cron install command.

 
 

php bin/magento cron:install

 

3. Verify the cron jobs were created

 
 

crontab -l

 

4. You should see entries like:

 
 

* * * * * /usr/bin/php /path/to/magento/bin/magento cron:run | grep -v "Ran jobs by schedule" >> /path/to/magento/var/log/magento.cron.log

 

5. Make sure the cron service is running.

 
 

sudo service cron status

 

# or

 
 

systemctl status cron

 
 

9. Security Enhancements for a Stable Environment

While optimization is crucial, don’t overlook security.

  • Server Firewall: Configure a server firewall to block malicious traffic.
  • DDoS Protection: Use Cloudflare or similar services for DDoS protection to shield your server from traffic spikes.
 
If you’re looking to further enhance your store's usability, don’t miss our guide on Tips and Tricks for Improving Magento Product Search.
 

Optimizing Magento for better performance is a combination of smart server choices (Apache vs. Nginx), caching strategies (Redis, Varnish), and server tuning. By applying these techniques, you can improve your website's speed, reduce server load, and enhance the user experience. Whether you're using Nginx or Apache, these optimizations can be tailored to fit your needs.


Was this answer helpful?

« Back