编程技术分享平台

网站首页 > 技术教程 正文

Nginx 备忘录 - 06. SSL 配置(nginx 备案)

xnh888 2024-09-11 11:03:08 技术教程 33 ℃ 0 评论

一、安装 http_ssl 模块

# 查看 nginx 是否有 ssl 模块
/opt/nginx/sbin/nginx -V

# 进入 nginx 源码,
# 重新编译 nginx, 启用 ssl 模块
./configure --prefix=/opt/nginx --with-http_ssl_module
make

# 备份原 nginx 执行文件
mv /opt/nginx/sbin/nginx \
/opt/nginx/sbin/nginx.old
# 将新编译好的可执行程序拷贝到之前的位置
cp /opt/nginx-1.26.1/objs/nginx \
/opt/nginx/sbin/

# 检查 nginx 是否正常
./nginx -t

二、阿里云申请 ssl 证书

1. 登陆阿里云购买并申请 ssl 证书:https://yundun.console.aliyun.com/?p=cas(阿里云也提供了免费证书的申请用于测试)

2. 证书申请下来后,选择你要使用的 Nginx 类型的证书,点击下载即可。

3. 下载解压后获得两个文件,之后需要配置到 Nginx 中:

  • 证书文件:www.liwy-nginx.com.pem
  • 私钥文件:www.liwy-nginx.com.key

三、自签名证书

如果只是用于测试,我们也可以使用本地生成的自签名证书:

# 生成私钥文件 private.key
openssl genpkey -algorithm RSA \
-out private.key

# 生成证书请求文件 server.csr
openssl req -new -key private.key \
-out server.csr

# 生成自签名证书 certificate.crt
openssl x509 -req -days 365 \
-in server.csr -signkey private.key \
-out certificate.crt

生成证书过程中,需要我们填写一些基本信息,最重要的是 Common Name,需要输入与服务器关联的域名: liwy-nginx.com。

最终我们得到两个文件,之后需要配置到 Nginx 中:

  • 私钥文件:private.key
  • 证书文件:certificate.crt

四、nginx 配置证书

server {
  # 监听 443 端口
  listen 443 ssl;
  # 绑定证书的域名
  server_name liwy-nginx.com;
  
  # 配置证书文件相对或绝对路径
  ssl_certificate /opt/nginx/conf/cert/certificate.crt
  # 配置私钥文件相对或绝对路径
  ssl_certificate_key /opt/nginx/conf/cert/private.key
}

如果想要将 HTTP 请求自动重定向到 HTTPS,可以做如下配置:

server {
  # 监听 80 端口
  listen 80;
  # 绑定证书的域名
  server_name liwy-nginx.com; 
   
  # 把 http 的请求转成 https
  return 301 https://$host$request_uri; 
}

五、防火墙开启 443 端口

firewall-cmd --zone=public --add-port=443/tcp --permanent
firewall-cmd --reload

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表