How to enable HTTP/2 in Nginx

Yobi Bina Setiawan
29 Jan 2025 · Backend and DevOps

To enable HTTP/2 in Nginx, follow these steps:

  1. Make sure your Nginx version supports HTTP/2: HTTP/2 is supported in Nginx version 1.9.5 or later. Check your version with:

    bash
    nginx -v

    If it's older than 1.9.5, you might need to update Nginx.

  2. Edit Nginx Configuration: Open the Nginx configuration file. The location of this file depends on your system, but common paths are /etc/nginx/nginx.conf or /etc/nginx/sites-available/default.

    Use a text editor like nano to open the file:

    bash
    sudo nano /etc/nginx/nginx.conf
  3. Enable HTTP/2 for your server block: In the server block for your site, modify the listen directive to enable HTTP/2 by adding the http2 option. It should look like this:

    nginx
    server { listen 443 ssl http2; server_name yourdomain.com; # SSL certificate and key ssl_certificate /path/to/your/certificate.crt; ssl_certificate_key /path/to/your/private.key; # Other configurations... }

    If you're using HTTP over port 80, it's recommended to redirect traffic to HTTPS, as HTTP/2 requires SSL/TLS.

  4. Check Nginx Configuration: Before restarting Nginx, ensure there are no syntax errors in the configuration:

    bash
    sudo nginx -t
  5. Restart Nginx: If the configuration test passes, restart Nginx to apply the changes:

    bash
    sudo systemctl restart nginx
  6. Verify HTTP/2 is working: You can verify that HTTP/2 is enabled by inspecting the response headers in a browser or using curl:

    bash
    curl -I https://yourdomain.com

    Look for HTTP/2 in the response headers.

That’s it! Your Nginx server should now be serving your site over HTTP/2.