Before touching Nginx, you need to have an SSL certificate ready. Buying one from Alibaba Cloud or applying for a free certificate are both workable options. The certificate application process is already documented in detail elsewhere, so the focus here is only on deployment.
Preparing the certificate files
Because the Nginx build already includes the SSL module, the next step is simply configuring the certificate.
After downloading the certificate package, extract it and upload the files to the server. The exact directory does not matter as long as it is easy to find later. In this case, the files were placed under root/card.
Editing nginx.conf
Open the Nginx configuration file. On this server it is located at /etc/nginx/nginx.conf, though on some systems it may be under /usr/local/nginx/conf.
Once inside, add or adjust the HTTPS and HTTP server blocks as needed:
http {
include mime.types; # 包含 MIME 类型定义
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
# HTTPS server block
server {
# 监听443端口(HTTPS)
listen 443 ssl;
# 【请修改】您的域名
server_name xxx;
# 启用 SSL (注意: "ssl on;" 已被弃用,直接使用 "listen ... ssl;")
ssl on;
# 【请修改】SSL 证书的 PEM 文件路径
ssl_certificate /root/card/www.xxxx.pem;
# 【请修改】SSL 证书的 KEY 文件路径
ssl_certificate_key /root/card/www.xxxx.key;
location / {
# 【请修改】代理转发的目标地址和端口(例如公网IP和项目端口号)
proxy_pass http://公网地址:项目端口号;
}
}
# HTTP server block for redirecting to HTTPS
server {
# 监听80端口(HTTP)
listen 80;
# 【请修改】您的域名
server_name huiblog.top;
# 将所有 HTTP 请求永久重定向到 HTTPS
rewrite ^(.*)$ https://$host$1 permanent;
}
}
A few values in this configuration must be replaced with your own:
server_nameshould be your domain name.ssl_certificateshould point to the uploaded.pemfile.ssl_certificate_keyshould point to the corresponding.keyfile.proxy_passshould forward traffic to your public server address and the port used by the project.
The HTTPS block listens on port 443 and uses the certificate files you provide. The HTTP block listens on port 80 and permanently redirects all requests to HTTPS.
Reloading Nginx
After saving the configuration, reload Nginx to apply the changes:
sudo systemctl reload nginx