Skip to content

Nginx Force HTTPS

Nginx Maps

  1. Create a new file on the server with a space-seperated list of old-to-new URLS:
    /old-url-1 /new-url-1
    /old-url-2 /new-url-2
    /old-url-3 /new-url-3 
    
  2. Include the map in your Nginx config:
    # Place this at the top of your nginx configuration
    map $request_uri $new_uri {
        include /path/to/redirects.map; # or any file readable by nginx
    }
    
  3. Make use of the map inside the server block:
    # if a redirect is be found in the map file it will use it
    server {
        if ($new_uri) {
           return 301 https://$new_uri;
        }
    }
    
  4. You may need to increase map_has_bucket_size within the http block:
    http {
        map_hash_bucket_size 256; # see http://nginx.org/en/docs/hash.html
    }
    
  5. Redirect all unmapped requests to their HTTPS equivalent
    server {
       if ($scheme = http) {
           return 301 https://$host$request_uri;
       }
    }
    
  6. Add headers to tell browsers they should only use HTTPS
    location / {
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    
        # re-write redirects to http as to https, example: /home
        proxy_redirect http:// https://;
    }
    
  7. Test the new config with nginx -t and then restart the nginx service