How to enable HTTP/2 in Nginx?

Dec 17, 2021 1 minute read
http2

There are many ways to improve your page loading time. One of them (the fastest one) is to optimize the HTTP server by enabling HTTP/2. Actually there is also HTTP/3, but it's not available in Nginx yet.

Start

Enabling HTTP/2 is very simple. I assume you got already installed Nginx in your host. Before we go, let's check what version you have. 

➜ nginx -v
nginx version: nginx/1.18.0 (Ubuntu)

Then let's open configuration file and update each listen directive to contain http2 keyword. In my case it's just a default one. As you can see below I got also SSL flag. You need to have SSL enabled because browsers allow HTTP/2 only via HTTPS.

# /etc/nginx/sites-available/default

#before
listen 443 ssl;

# after
listen 443 http2 ssl;

Save your file, and restart Nginx with the following command

➜ nginx -s reload

That's it!

Now your Nginx supports the HTTP/2 protocol. You can check it with curl command.

➜ curl -I https://mevelix.com
HTTP/2 200 
...

What is the effect?

After this change, on one of the random articles, the loading time dropped from 598 ms to 379 ms 😮. As you can see the result is pretty good. Especially for sites that are serving a lot of assets in during page load.

Summary

The HTTP/2 and then HTTP/3 will become the standard quickly so be sure to enable them. Most browsers support them, but http servers do not always enable them by default. If you are interested more on web performance please check web.dev site, there are a lot of tips and articles on that.

Disclaimer: The opinions expressed here are my own and do not necessarily represent those of current or past employers.
Comments (0)