How do I redirect traffic to https for my Nginx site?
If I am running a site on Nginx, how do I get my site to redirect from http to https?
2 Replies
To get this redirect working, you will have to make some changes to your Nginx configurations file. You need to ensure that your first server block is pointed towards the http port 80 and the second block is ported towards 443 for https.
server {
listen 80;
server_name example.com www.example.com;
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl;
server_name example.com www.example.com;
# ssl configuration
ssl on;
ssl_certificate /path/to/certificate.crt;
ssl_certificate_key /path/to/private.key;
if ($http_host = www.example.com) {
return 301 https://example.com$request_uri;
}
]
The above example shows how an https redirect configuration should look for an Nginx site. Specifically, the return 301 is the redirect and will send anything from www.example.com
to https over port 443. If you'd like further reference, I recommend reviewing this page Redirects with HTTPS.
My experience with the example above is good but has problem when user types https://www.something.com, the page can redirect but the connection is unsecured.
Much better with
server{
listen 80;
listen 443 ssl;
server_name www.something.com something.com;
return 301 https://something.com$request_uri;
}
so when client user types https://www.something.com the page can still redirect to https://something.com in secured connection. Try it!