How To Redirect HTTP to HTTPS in Nginx

A simple and effective way to send your site's traffic to SSL.

A while back I moved my site to full-time TLS. This is great for users since it provides both security through an encrypted connection, and authentication to verify that what they’re getting is actually coming from me, without alteration or interception. However, I needed to make sure any requests to non-TLS locations were redirected to their new TLS-protected URL. Luckily Nginx makes this really simple. Here’s the code you need to add to your server configuration:

server {
    server_name example.com;
    return 301 https://$host$request_uri;
}

You’ll need to replace example.com with your domain. This creates a new host in Nginx listening on your HTTP port. Whenever a request comes in to the domain listed in server_name, Nginx will redirect the user to that same URL at the new location. That way the user is taken to the exact page they were expecting.

What’s more, this generates a 301 Moved Permanently header, which means that the client knows any future requests to this URL should instead be served the page at the redirected location. This is also great for search engines, since they’ll be made aware that the page has moved and will update their records to use the new URL, without affecting your page’s search rank.

This configuration works for other redirect circumstances too. If your site has moved to a new domain or subdomain, or a new directory on your existing domain, you can modify the code above to reflect that.

Update September 24, 2015: based on feedback in the comments of the post and in documentation for Nginx, I’ve updated this post to use a better redirect syntax. Thanks to everyone who contributed input on this!

comments powered by Disqus