How to Force HTTPS in Nginx: HTTP to HTTPS 301 Redirect
Enabling HTTPS across your entire website enhances security. While the process can sometimes be tricky, this article provides a straightforward solution that requires minimal program modifications. Instead, you can configure it directly in your web server (Nginx) to redirect all traffic from port 80 (HTTP) to HTTPS via a 301 redirect. This is the method currently used by Xiaoz Blog.

1. Prerequisites
This method applies specifically to Nginx web services. It is recommended to use the LNMP One-Click Installer by Junge or OneinStack, though compiling Nginx manually is also supported.
2. Modify the Host Configuration File
For LNMP or OneinStack installations, the configuration file is typically located at /usr/local/nginx/conf/vhost/youdomain.com.conf. Add the following configuration snippet to this file:
server
{
listen 80;
server_name xiaoz.me www.xiaoz.me;
rewrite ^(.*) https://blog.xiaoz.org$1 permanent;
}
The configuration above ensures that any HTTP request to xiaoz.me or www.xiaoz.me is permanently (301) redirected to https://blog.xiaoz.org. Below is a complete configuration example for reference:
server {
listen 443;
ssl on;
ssl_certificate /data/ssl/xiaoz.me.crt;
ssl_certificate_key /data/ssl/xiaoz.me.key;
server_name xiaoz.me www.xiaoz.me;
index index.html index.htm index.php;
... // Additional SSL settings
... // Additional server settings
}
server
{
listen 80;
server_name xiaoz.me www.xiaoz.me;
rewrite ^(.*) https://blog.xiaoz.org$1 permanent;
}
After modifying the configuration, remember to reload Nginx:
service nginx reload
3. Test with CURL
Finally, verify that HTTP requests are being 301 redirected to HTTPS using CURL:
curl -I www.xiaoz.me
For more details on configuring SSL in Nginx, refer to the tutorial: How to Deploy SSL Certificates in Nginx.

Recommended Reading: