UPDATE: Just to clarify, this blog post is purely about how to set up the redirects to get all users over to a URL that uses ‘https://www.’ in one redirect. It does not cover how to set up NGINX SSL in a way that mitigates all known SSL vulnerabilities (and even if it did, it would quickly become outdated). I highly recommend that you run your SSL sites through a test (such as the one at https://www.ssllabs.com/ssltest/) to find out what, if any, SSL vulnerabilities your site has, and make the recommended changes to fix them. Back to the original post 😉
Recently I splurged and bought a wildcard SSL certificate for the cryptkcoding domain. Because I have the certificate, I figured that I would set up my blog to use SSL by default (before it was a self-signed certificate, and I only used it for the back-end). Since I was poking at the nginx configuration to get the redirects all set up, I figured I would write a blog post on how to have nginx force all visitors over to both the www URL as well as enforce https. And we will be doing this right, no matter what visitors will only get one redirect (unless they go straight to the https://www site).
Here is the relevant part of the configuration:
## Force all users to https://www server { listen 80; ## IPv4 listen [::]:80; ## IPv6 server_name yoursite.com www.yoursite.com; return 301 https://www.yoursite.com$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; server_name yoursite.com; ssl_certificate /etc/nginx/ssl/www.yoursite.com.bundle.crt; ssl_certificate_key /etc/nginx/ssl/www.yoursite.com.key; return 301 https://www.yoursite.com$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; server_name www.yoursite.com; ssl_certificate /etc/nginx/ssl/www.yoursite.com.bundle.crt; ssl_certificate_key /etc/nginx/ssl/www.yoursite.com.key; }
No matter what, your visitors will end up on the encrypted and www versions of your website. The best part is that none of this redirect config will ever touch your websites code, it all happens purely in nginx. If you are running a PHP based site (likely with php-fpm) then you don’t have to worry about the overhead of connecting back to php-fpm just to have it return a redirect.
This does obviously rely on you having a valid SSL certificate for www.yoursite.com (that said, it will still work with self-signed ones, you visitors will just need to add an exception to their browser for your website).
Let me know how this works out for you!
Dustin says:
Thank you! Finally someone that confirmed this is the best way to do this. I setup my config like you did above but I always like to check if there is others doing it like this. Everyone else wanted to use IF statements, which we know are bad 🙂
https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/