温馨提示×

linux nginx怎样配置SSL

小樊
49
2026-10-19 14:13:43
栏目: 云计算

在 Linux 上使用 Nginx 配置 SSL(HTTPS) 通常包含以下几个步骤:申请/生成证书、配置 Nginx、重启并验证。下面以 自签名证书 和 Let’s Encrypt 免费证书 两种方式说明。


一、准备工作

确保已安装 Nginx:

nginx -v

如未安装:

# Ubuntu / Debian
sudo apt update
sudo apt install nginx

# CentOS
sudo yum install nginx

二、使用自签名证书(测试用)

1. 生成私钥和证书

sudo mkdir -p /etc/nginx/ssl
cd /etc/nginx/ssl

sudo openssl req -x509 -nodes -days 365 \
  -newkey rsa:2048 \
  -keyout example.com.key \
  -out example.com.crt

按提示填写信息(Common Name 填域名或 IP)。


2. 配置 Nginx

编辑站点配置:

sudo vim /etc/nginx/conf.d/ssl.conf

示例配置:

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    location / {
        root /usr/share/nginx/html;
        index index.html;
    }
}

# HTTP 重定向到 HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

3. 测试并重启

sudo nginx -t
sudo systemctl restart nginx

访问:

https://example.com

(浏览器会提示不安全,属正常现象)


三、使用 Let’s Encrypt 免费证书(推荐)

1. 安装 Certbot

# Ubuntu
sudo apt install certbot python3-certbot-nginx

# CentOS
sudo yum install epel-release
sudo yum install certbot python3-certbot-nginx

2. 自动申请并配置

sudo certbot --nginx -d example.com -d www.example.com

按提示操作,Certbot 会自动:

  • 申请证书
  • 修改 Nginx 配置
  • 设置 HTTP → HTTPS 跳转

3. 自动续期

sudo certbot renew --dry-run

Certbot 通常已配置 systemd 定时任务。


四、常见优化(可选)

开启 HSTS

add_header Strict-Transport-Security "max-age=31536000" always;

禁用旧协议

ssl_protocols TLSv1.2 TLSv1.3;

五、防火墙注意

确保放行 80 和 443:

sudo ufw allow 80
sudo ufw allow 443

如果你有 具体域名、系统版本(Ubuntu/CentOS)或反向代理需求(如 Node、Java),我可以给你更精确的配置示例。

0 踩