0
0
NginxHow-ToBeginner · 3 min read

How to Enable HTTP/2 in Nginx: Simple Steps

To enable http2 in Nginx, add the http2 parameter to the listen directive inside your server block, typically on port 443 for HTTPS. Ensure your server uses SSL/TLS because HTTP/2 requires a secure connection in Nginx.
📐

Syntax

The listen directive in Nginx controls which IP and port the server listens on. Adding http2 enables HTTP/2 protocol support. This is usually combined with SSL/TLS settings for secure connections.

  • listen 443 ssl http2;: Listens on port 443 with SSL and HTTP/2 enabled.
  • ssl_certificate and ssl_certificate_key: Specify your SSL certificate files.
nginx
server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    # Other server settings
}
💻

Example

This example shows a minimal Nginx server block with HTTP/2 enabled on HTTPS port 443. It includes SSL certificate paths and the http2 parameter in the listen directive.

nginx
server {
    listen 443 ssl http2;
    server_name www.example.com;

    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;

    location / {
        root /var/www/html;
        index index.html;
    }
}
Output
Nginx starts successfully and serves content over HTTPS with HTTP/2 protocol enabled.
⚠️

Common Pitfalls

Common mistakes when enabling HTTP/2 in Nginx include:

  • Forgetting to add http2 in the listen directive.
  • Trying to enable HTTP/2 on port 80 (non-SSL), which Nginx does not support.
  • Missing or incorrect SSL certificate paths causing Nginx to fail to start.
  • Not reloading or restarting Nginx after configuration changes.

Always check your Nginx error logs if HTTP/2 does not work as expected.

nginx
## Wrong way (HTTP/2 on port 80 without SSL)
server {
    listen 80 http2;
    server_name example.com;
}

## Right way (HTTP/2 with SSL on port 443)
server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
}
📊

Quick Reference

Tips for enabling HTTP/2 in Nginx:

  • Use listen 443 ssl http2; in your server block.
  • Ensure valid SSL certificates are configured.
  • Reload Nginx after changes with sudo nginx -s reload.
  • Check nginx -t to test configuration syntax before reloading.

Key Takeaways

Add the 'http2' parameter to the 'listen' directive on port 443 with SSL enabled.
HTTP/2 requires HTTPS in Nginx; it cannot run on plain HTTP (port 80).
Always configure valid SSL certificates to enable HTTP/2.
Test your Nginx configuration with 'nginx -t' before reloading.
Reload Nginx after changes to apply HTTP/2 support.