Redirecting plain HTTP traffic to HTTPS forces browsers and API clients onto an encrypted connection, preventing credentials and session cookies from crossing the network in cleartext. It also consolidates a single canonical scheme for the site, reducing mixed-content warnings and inconsistent caching behavior.

In Nginx, the simplest pattern is a dedicated server block listening on port 80 that immediately returns a permanent redirect to the HTTPS URL. Using a return keeps the redirect fast and predictable, while $request_uri preserves the full path and query string without rewrite logic.

HTTPS should be working before enforcing redirection, because permanent redirects can be cached by clients and proxies and a broken TLS virtual host can cause effective lockouts. If port 80 is required for load balancer health checks or ACME HTTP-01 validation, ensure those endpoints still succeed or add an exception. Always validate syntax with nginx -t before reloading to avoid downtime from configuration errors.

Steps to redirect HTTP to HTTPS in Nginx:

  1. Confirm the HTTPS virtual host returns a successful response.
    $ curl -I https://example.com/
    HTTP/1.1 200 OK
    Server: nginx
    Date: Sun, 14 Dec 2025 12:34:56 GMT
    Content-Type: text/html; charset=UTF-8
    ##### snipped #####
  2. Open the Nginx virtual host configuration file for the domain.
    $ sudoedit /etc/nginx/sites-available/example.com

    Common locations include /etc/nginx/sites-available/<site>/ (often enabled via /etc/nginx/sites-enabled/) and /etc/nginx/conf.d/<site>.conf/.

  3. Add an HTTP server block that redirects all requests to HTTPS.
    server {
        listen 80;
        server_name example.com www.example.com;
    
        return 301 https://$host$request_uri;
    }

    Use return 308 when preserving HTTP methods matters, and use 302 temporarily during testing to reduce cached-redirect surprises.

    Enforcing the redirect before HTTPS is reachable can break access for clients that only know the HTTP URL.

  4. Test the Nginx configuration for syntax errors.
    $ sudo nginx -t
    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
  5. Reload Nginx to apply the change.
    $ sudo systemctl reload nginx

    On systems without systemd, reload with sudo nginx -s reload.

  6. Verify the redirect by checking the Location header on an HTTP request.
    $ curl -I http://example.com/account/login?next=%2Fdashboard
    HTTP/1.1 301 Moved Permanently
    Server: nginx
    Date: Sun, 14 Dec 2025 12:35:20 GMT
    Content-Type: text/html
    Content-Length: 169
    Connection: keep-alive
    Location: https://example.com/account/login?next=%2Fdashboard
    ##### snipped #####
Discuss the article:

Comment anonymously. Login not required.