Nanfeng

Notes on software development, code, and curious ideas

Redirecting HTTP to HTTPS with Nginx

After moving the blog to a cloud server, HTTP worked but browsers marked it as insecure. The usual solution is to install a valid TLS certificate and redirect port 80 to the HTTPS URL.

Configure Nginx

Create or edit the site’s virtual-host file. Use a dedicated HTTP redirect block:

1
2
3
4
5
6
7
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;

return 301 https://$host$request_uri;
}

Serve the site over TLS in a separate block:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com www.example.com;

ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;

root /www/wwwroot/hexo;
index index.html;

location / {
try_files $uri $uri/ =404;
}
}

If Nginx is proxying an application rather than serving static Hexo files, replace the root section with a proxy_pass location and forward the host and protocol headers.

Test before reloading:

1
2
sudo nginx -t
sudo systemctl reload nginx

Confirm that the certificate covers every hostname, renews automatically, and that firewall/security-group rules allow ports 80 and 443. TLS 1.0 and 1.1 are obsolete and should not be enabled in a new configuration.

+