本指南旨在提供一个关于如何在 Nginx 中配置 SSL/HTTPS 的实践总览,包括必要的环境准备、SSL 模块的编译安装、使用 OpenSSL 生成自签名证书的步骤,以及最终 Nginx 服务器的详细配置示例。旨在帮助您快速为 Nginx 服务启用加密通信。

完整 Nginx 相关知识概览,请参考 MOC - Nginx 代理

1. Nginx SSL 模块的编译与依赖

在为 Nginx 配置 HTTPS 之前,确保您的 Nginx 编译时包含了 http_ssl_module。如果您的 Nginx 是通过源码编译安装的,可能需要预先安装一些库。

  • 1.1 Nginx SSL 模块编译依赖

    • 介绍编译 Nginx SSL 模块所需的系统依赖库,如 pcre, zlib, openssl 等的安装方法。
    • # 原始内容将移动到这里
      yum -y install gcc-c++ autoconf automake make
      yum -y install pcre pcre-devel
      yum -y install zlib zlib-devel make libtool
      yum -y install openssl openssl-devel
  • 1.2 Nginx 编译安装 SSL 模块

    • 详细说明如何在 Nginx 编译时添加 http_ssl_module 模块的 configure 命令,以及 makemake install 步骤。
    • # 原始内容将移动到这里
      ./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
      make
      make install
       
      # 如果错误
      ./configure --prefix=/opt/openresty \
                  --with-luajit \
                  --without-http_redis2_module \
                  --with-http_iconv_module \
                  --with-http_postgres_module \
                  --with-openssl=/usr/local/openssl

2. HTTPS 证书的生成

为了启用 HTTPS,您需要一个服务器证书和对应的私钥。本节将指导您使用 OpenSSL 工具链生成自签名 SSL 证书。在实际生产环境中,您通常需要从可信任的证书颁发机构 (CA) 获取证书。

  • 2.1 OpenSSL 生成 Nginx HTTPS 证书
    • 提供使用 openssl 命令生成私钥 (.key)、证书签名请求 (.csr) 和最终自签名证书 (.crt) 的详细步骤。
    • 解释每一步的含义,以及 Common Name 等重要参数的设置。
    • # 原始内容将移动到这里
      #此步用于生成私钥,会提示输入密码,密码后面步骤需要用到;jason.key为私钥的名字,文件名可自己定
      openssl genrsa -des3 -out jason.key 1024
      #此步用于生成csr证书,jason.key为上一步骤生成的私钥名,jason.csr为证书,证书文件名可自定
      #在此步过程中,会交互式输入一系列的信息(所在国家、城市、组织等),其中Common Name一项代表nginx服务访问用到的域名,我这里是本地测试,所以可以随意定一个jason.com,并在本地host文件中将此域名映射为127.0.0.1
      openssl req -new -key jason.key -out jason.csr
      #此步用于去除访问密码,如果不执行此步,在配置了ssl后,nginx启动会要求输入密码
      #jason.key为需要密码的key,jason-np.key为去除访问密码的key文件
      #操作过程中会要求输入密码,密码为生成key文件时的密码
      openssl rsa -in jason.key -out jason-np.key
      #此步用于生成crt证书
      #jason.crt为第2步生成的csr证书名称,jason.crt为要生成的证书名称
      openssl x509 -req -days 366 -in jason.csr -signkey jason-np.key -out jason.crt

3. Nginx HTTPS 服务器配置

在证书准备好之后,最后一步是在 Nginx 配置文件中指定 SSL 证书和密钥,并启用 HTTPS 服务器块。

  • 3.1 Nginx HTTPS_SSL 服务器配置示例
    • 提供 Nginx server 块中关于 listen 443 sslssl_certificatessl_certificate_keyssl_ciphers 等指令的详细配置示例和解释。
    • # 原始内容将移动到这里
      # HTTPS server
       
          server {
              listen       443 ssl;
              server_name  front;
       
              ssl_certificate      ./ssl/jason.crt;
              ssl_certificate_key  ./ssl/jason-np.key;
       
              #ssl_session_cache    shared:SSL:1m;
              ssl_session_timeout  5m;
       
              ssl_ciphers  HIGH:!aNULL:!MD5;
              ssl_prefer_server_ciphers  on;
       
              location / {
                  root   html;
                  index  index.html index.htm;
              }
          }