Complete guide to Magento 2 performance optimization. Steps, codes, tips.

Complete guide to Magento 2 performance optimization. Steps, codes, tips.

Boosting website speed is always good practice. Have you ever thought how critically a site speed improves performance? How one single factor can make a big difference in your site's user experience.  

Performance matters. It's hardly a secret that high-performing sites result in a better conversion rate. We believe you wish your store provided the best ever website speed to your clients' advantages. We bet that everyone wants to get a perfect 100% score on Google PageSpeed.

For this reason, we offer many opportunities for Magento 2 performance improvement. Read the guide to website performance optimization and choose the technique that could significantly affect your site.

What does page speed rank take into account?

You do need to understand the purpose of website performance optimization. Speed or Score?

In fact, the most important metric for your site performance is the page load time. It is about the full page load time that takes to fully render the content on a page as well as the time to first byte (TTFB) what means a time spent for waiting for the initial response from the web server.

Quick page loading for your visitors is when speed is measured in seconds. Even taking into account that Google estimates the entire website speed as a ranking factor, you still have to focus on those first seconds.

TTFB is directly related to that. Thus we highly recommend you to consider it like the very first of multiple tasks you are gonna accomplish in order to get a high page speed score in the end.

Some other performance enhancements will be significant after optimizing those first bytes. So you just need to take TTFB as a part of your Magento 2 website optimization task.

We can then ask,

What would be the next step for speeding up TTFB? How to ensure a faster server response time?

Choosing fast hosting

In fact, the reduced server response time is directly correlated to enhanced hosting speed.

Good news is the web host is a thing you really can control over. You are able to choose the right hosting server with best-expected speed and proper solutions that help reduce TTFB.

Well, Google says your server response time should be under 200ms. Let’s see what hosts offer the fastest TTFB, and what else must-have services the web hosting company should offer you.

But, honestly, we recommend using Magento Commerce Cloud hosting platform. We think it offers an established and perfectly organized infrastructure with a bunch of built-in high availability features.

If you're looking for a hosting solution with extensive experience in Magento, this is evident to use Magento Commerce Cloud. Here are some reasons why we choose it:

  • built-in Varnish caching for enhanced performance
  • accommodated workflow
  • includes all required PHP extensions, and, of course, is PHP 7 ready
  • correct domain configuration or domain settings
  • optimized PHP accelerator to help fasten the hosting plan
  • fast CDN to help users get a lightning-fast site
  • fully managed services like MySQL, Elasticsearch, Redis, RabbitMQ, without requiring external plugins

With an automated hosting platform, you also get a great feature -  New Relic APM (Performance Monitoring). It allows monitoring your sites' performance.

Due to this hosting solution, you can also be certain your website is always updated in a timely manner with all possible changes made by Magento.


Besides, whatever host you want to select, try to avoid using shared hosting. It simply doesn't support the memory limits required by Magento. However, if the server sizes meet the needs of your store, for instance, it is enough for a number of daily visitors, go on to use it. 

We also suggest considering the host with a data center closest to the majority of your clients. Focus on your country-based Magento web hosting provider. It will definitely make your store faster for your local visitors.

Let us briefly summarize the main requirements for hosting solutions. You’d better focus on host:

  • with servers that are PHP 7 ready
  • that includes an optimized stack with Linux-based OS, Nginx, PHP-FPM
  • that works best with built-in Magento cache as Varnish or other caching solutions such as Redis, or ElasticCache
  • that include features such as SSL certificate, SSD-based storage, CDN
  • that provides PHP acceleration
  • with the available option to enable GZIP compression
  • that supports HTTP/2

One more important thing is a web server that is used by a hosting company. Most of the best hosts use Apache and NGINX servers. They are both engineered for optimal performance, but they still differ in speed, scalability, technical knowledge requirement, and configuration.

Later we’re gonna be talking about the page speed optimization solutions separately for Apache and Nginx. Keep reading.

Optimizing web server

After moving step-by-step through a variety of hosting, we focus on the other priority - the web servers which comply with the Magento 2 system requirements. Magento best runs on Apache 2.2-2.4 and Nginx 1.8 (and later).

Which server is best? Let’s take it up briefly.

Magento itself suggests using Nginx web server just because it contains settings for better performance. Plus, hundreds of web hosts are offering Nginx as a good solution to serve both dynamic and static website content while handling a huge number of requests. Look at some fundamental characteristics:

  • Nginx serves static content about 2.5 times faster than Apache even dealing with the immense amounts of traffic.
  • NGINX got support for dynamic module loading.
  • NGINX supports FastCGI and SCGI handlers for serving dynamic content scripts such as PHP.

Lots of our clients still prefer Apache over Nginx. Users like this web server for a big number of features such as:

  • A vast number of modules available to extend it.
  • Compatibility with far more third-party technologies.
  • Built-in PHP support.
  • Better supports loading various dynamic modules.

Considering the fact the Magento 2 fully supports both Nginx and Apache web servers, it’s up to you which one is right for your eCommerce site. The only recommendation for you is to pay attention if the web hosting service helps you with a server configuration and setup.

3 must-haves for optimizing on server-side

Enabling browser caching

By enabling browser caching of static files or files you actually don’t change often, you speed up the secondary loads to these pages. It may increase the load time, so many users disable the option. But we highly recommend leveraging browser caching as it is essential for SEO purposes. You just have to add Expires Headers to reduce the time the server requires to connect with the browser.

See the ways of adding Expires Headers for Nginx and Apache servers separately. You have to paste the next code on your site configuration file.


#browser caching of static assets
location ~*  \.(jpg|jpeg|png|webp|gif|ico)$ {
  expires 31d;

#browser caching of css
location ~*  \.(css)$ {
  expires 6d;

#browser caching of js
location ~*  \.(js)$ {
  expires 31d;


Header set Connection keep-alive

    # Expires Headers - 2678400s = 31 days
      ExpiresActive On
      ExpiresDefault "access plus 1 seconds"
      ExpiresByType text/html "access plus 7200 seconds"
      ExpiresByType image/gif "access plus 2678400 seconds"
      ExpiresByType image/jpeg "access plus 2678400 seconds"
      ExpiresByType image/png "access plus 2678400 seconds"
      ExpiresByType text/css "access plus 518400 seconds"
      ExpiresByType text/javascript "access plus 2678400 seconds"
      ExpiresByType application/x-javascript "access plus 2678400 seconds"

    # Cache Headers
      # Cache specified files for 31 days
      Header set Cache-Control "max-age=2678400, public"
      # Cache HTML files for a couple hours
      Header set Cache-Control "max-age=7200, private, must-revalidate"
      # Cache PDFs for a day
      Header set Cache-Control "max-age=86400, public"
      # Cache Javascripts for 31 days
      Header set Cache-Control "max-age=2678400, private"

Gzip compression

This solution is a must-have for speeding up your site as it reduces the size of the files, and the server will need less time to process them. Enabling Gzip compression results in a significant reduction in the weight and speed of page loading.  

To enable Gzip, please paste the following code to site configuration file.  


gzip on;
gzip_disable "msie6";

gzip_comp_level 6;
gzip_min_length 1100;
gzip_buffers 16 8k;
gzip_proxied any;


gzip_vary on;


        ## enable resulting html compression
       php_flag zlib.output_compression on
        SetOutputFilter DEFLATE
        AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml application/x-javascript application/x-httpd-php
        BrowserMatch ^Mozilla/4 gzip-only-text/html
        BrowserMatch ^Mozilla/4\.0[678] no-gzip
        BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
        BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
        SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip

Implementing HTTP/2

Normally, the latest current versions of Apache and Nginx servers have added HTTP/2 support. You can also check the HTTP/2 browser support and availability by using an online tool.

Optimizing the PHP performance

The next point of significance for speeding up Magento 2 site is PHP performance optimization.

The PHP code execution takes about 70% of the TTFB time. It is crucial to get it efficient.

Therefore you just have to use the fastest PHP interpreter and configure it well.

The next step is optimizing PHP code to make it execute more quickly, and perform fewer input and output operations. Look at some tips on how to make PHP run efficiently:

First of all you have to set PHP options required by Magento 2:

  • Set the PHP memory limit.
  • Set the system time zone for PHP.
  • Activate the latest PHP version, that is required for Magento 2.3 and later.

Use the PHP accelerators for code optimization. It helps you to reduce server load and increase the speed of your PHP code. Magento 2 highly recommends activating the OpCache module to get maximum speed. The core of the PHP accelerator is to improve the performance of PHP scripts by caching them. Please mention, in case you use Nginx, you must install PHP FPM because Nginx doesn’t include native PHP processing.

Disable the unwanted PHP modules. Magento 2 also recommends limiting the list of active PHP extensions to those that are highly required for Magento functionality. By reducing the number of extensions you just reduce the memory utilized and improve performance. You have also to keep track of what PHP modules conflict. For instance, some users don't disable xdebug on a production server, and hence, it skews the overall performance numbers.

See more about PHP performance optimization.

Then our conclusion is that stores that run the latest supported version of PHP, result in a much faster website and run more efficiently. For optimal performance, we strongly recommend running Magento 2 with PHP 7.2 and later.

Tuning MySQL

Considering the fact, MySQL can run more than tens of thousands simple queries per second, it is by no means surprising that this is the most popular system for storing data.

As data volumes grow, your MySQL database might run slowly, and queries take longer to execute. Our common purpose is to increase Magento 2 site speed. Therefore we suggest configuring MySQL settings correctly in order to improve the overall speed of your database server.

Magento versions 2.1.2 and later are compatible with MySQL 5.7.x. Just follow general Magento 2 recommendations on how to tune MySQL in order to optimize MySQL queries for faster database performance.

Optimizing Magento 2 speed settings

Time to optimize your website speed on Magento 2 side. The superbness of Magento 2 is in having a pretty good list of possible optimizations obtained by default. We are gonna list them by way of explaining each one briefly.


There is no reason to explain why the website caching is important. Faster server response time, better user experience, higher SEO ratings. The only question remaining is the caching solutions.

Well, the Magento 2 package comes with the built-in PageCache module as well as integrated Varnish Cache. When offering the first solution only for development purposes, the Varnish application is highly recommended to reduce the response time. It is supposed to be a much faster and flexible option. Furthermore, Magento 2 settings include Advanced Varnish configuration. If you are still hesitating which cache works better - Varnish or Built-in, just have a look at some speed test results  here.

Redis is also supported to cache data for production mode. It is just considered to be more easy to use. The choice is yours.

Warming up the cache

We are talking about speedy browsing experience for every user, right? Then you also should provide the fastest page view for a first-time visitor. This is why we suggest you warm up the cache. You can add a full page warmer/crawler extension. It will cache all possible newly saved pages automatically.

Enabling merge CSS, JavaScript

The next possible Magento 2 speed optimization is minifying HTML, JS and CSS files. It makes sense because a minified code is parsed, compiled and loaded faster. It is also a way to improve the Google PageSpeed score.

By default, you can easily enable CSS/JS Minification in the Magento configuration. But sometimes big CSS files still take a long time to load and a built-in Magento 2 CSS optimization strategy is not enough. To increase Magento 2 speed, you need to focus on setting critical CSS or in other words prioritizing visible content. That way you' ll reduce the size of the above-the-fold content within the HTML structure, and make it loaded first. Some  Magento 2 speed modules include the advanced CSS settings which allow you to set the generated critical CSS.

Have a look at some other tips on how to improve Magento 2 performance within its default functionality:

  • Check if you disabled a developer mode while already running store in production mode. It really matters for making your website faster.
  • Inspect every 3rd-party extension installed. Some of them lead to excessive load times. You can use web speed test tools to define which take the most time to execute.

Additional optimization with Magento 2 Page speed tool

Several times over the article we mentioned a solution that is very powerful in features that expand the Magento 2 performance. Magento 2 Page Speed extension was developed to increase your web pages speed. It comes with a bunch of practices proven to get your site at the top of Google search rating.

Have a look at numerous things that show why using the module is a must.

Advanced CSS settings

Merge / Minify CSS

Previously we talked about TTFB - faster starting load time. So, merging CSS files is an idea when it comes about the faster finishing load time.

M2 Page Speed module allows you to merge CSS styles, and not only minify them. This reduces code that should be loaded, therefore the entire web page will be loaded faster.

Optimize CSS delivery

The module includes settings that allow adding inline CSS necessary for faster display the above fold area of your page.

Enable critical CSS

The module allows generating critical CSS to render above-the-fold content by including it directly in the HTML response. That way there will be loaded only the minimum amount of CSS required to render the top visible part of the page. Good idea to speed up your website.

Advanced JS settings

M2 Page Speed extension comes with lots of good practices to make JavaScript run faster. With the module you will be able to:

  • merge / minify JS files
  • deferred running all JS code on the page
  • enable using custom JS code unpacking
  • generate optimized JS bundle
  • use the advanced JavaScript bundling method

We'd like to focus on the last-mentioned option. Despite the many developers suggest disabling js. bundling, we still recommend using it for getting the faster server response time. Furthermore, we offer to use the innovative bundling algorithm provenly better Magento 2 performance.

Innovative JS bundling method

M2 Page Speed extension enables the advanced requires js bundling that allows you to build the separate bundles for each page of your site. It combines the default Magento bundling and r.js optimizer methods and adds the default bundle.

As a result, you would add only the necessary JS files for a certain page like separate bundle-product.js for each page of your Magento 2 store. For instance, you can put all checkout-related stuff into one bundle and load it only on the checkout page. See more.

With the Page Speed module JS bundling method, we promise an increased Page Speed score.


Advanced image optimization settings

By speeding up image delivery you can also improve your page loading time.

In order to prevent images slow down your website, we recommend implementing some optimization techniques provided by Page Speed module.

Lazy-loading for images

The feature helps browser load only pages which are in the browser's viewport. The module includes custom lazy loader configuration options: auto specify image dimensions, offset, placeholder field, and offset for mobile devices.

WebP images support

WebP is Google's alternative image format that compresses your images to a smaller size than a JPG file. Smaller image files make your website load faster in times. The Page Speed extension supports WebP image detecting and generating in your Magento 2 site.

Summarizing the benefits of Page Speed module, we’d like to mention one more option.

HTTP/2 push server preload feature

When a server HTTP/2 push enabled, the browser starts rendering the page much faster as it gets the js files, scripts, and fonts loaded via HTTP 2 protocol. It looks like you send content in advance that the visitor needs for the requested page.

The point is the Page Speed module contains so many techniques to help you significantly improve your Magento 2 site performance. Visit the module page or follow the user guide to learn more.


Getting your store close to 100/100 on Google Pagespeed tests is not an easy task. However, we’ ve got the best results possible for our SwissUpLabs website. We use different speed optimization practices and know how they work. And we are glad to share with you our positive experience.

We hope the guide adds value to your search queries on how to increase Magento 2 speed. In case you used to implement other techniques, please tell us about them in the comments. We love learning, too.

You can also review some more guides that will help you to improve your Magento website:

Popular Magento Themes & Extensions

Leave a Reply