温馨提示×

linux nginx怎样开启https

小樊
43
2026-09-29 03:11:26
栏目: 智能运维

在 Linux 上使用 Nginx 开启 HTTPS,通常步骤如下(以自签证书或Let’s Encrypt 免费证书为例):


一、前提条件

  1. 已安装 Nginx
nginx -v
  1. 有域名(公网 HTTPS 建议用域名)
  2. 服务器 80 / 443 端口可访问

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

1. 安装 certbot

CentOS / Rocky / Alma

yum install epel-release -y
yum install certbot python3-certbot-nginx -y

Ubuntu / Debian

apt update
apt install certbot python3-certbot-nginx -y

2. 自动申请并配置 HTTPS

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

按提示操作,certbot 会:

  • 自动申请证书
  • 修改 Nginx 配置
  • 开启 443 端口
  • 设置 HTTP 跳转 HTTPS

3. 测试自动续期

certbot renew --dry-run

三、手动配置 Nginx HTTPS(自签证书示例)

1. 生成私钥和证书

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

openssl genrsa -out server.key 2048
openssl req -new -x509 -days 365 -key server.key -out server.crt

2. 配置 Nginx

编辑站点配置:

vim /etc/nginx/conf.d/https.conf

示例:

server {
    listen 443 ssl;
    server_name localhost;

    ssl_certificate     /etc/nginx/ssl/server.crt;
    ssl_certificate_key /etc/nginx/ssl/server.key;

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

server {
    listen 80;
    server_name localhost;
    return 301 https://$host$request_uri;
}

3. 检查并重载 Nginx

nginx -t
systemctl reload nginx

四、防火墙放行

# firewalld
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

# 或 iptables
iptables -I INPUT -p tcp --dport 443 -j ACCEPT

五、验证

浏览器访问:

https://你的域名

六、常见问题

  • ❌ 证书不受信任 → 自签证书需手动信任
  • ❌ 无法访问 443 → 检查安全组 / 防火墙
  • ✅ 生产环境强烈推荐 Let’s Encrypt

如果你告诉我:

  • 系统版本(CentOS / Ubuntu)
  • 是否用域名
  • 是否 Docker / 面板(宝塔等)

我可以给你更精确的配置。

0 踩