Windows Nginx 本地 SSL 配置步骤

1. 下载并安装 Nginx

  • 访问 Nginx 官方网站 下载 Windows 版本的 Nginx。

  • 解压到指定目录,如 C:\nginx

2. 生成自签名 SSL 证书

  • 打开命令提示符,使用 OpenSSL 生成私钥和证书:

    openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout C:\nginx\conf\ssl\localhost.key -out C:\nginx\conf\ssl\localhost.crt
  • 按照提示输入相关信息,完成后会在 C:\nginx\conf\ssl 目录下生成 localhost.keylocalhost.crt 文件。

3. 配置 Nginx

  • 打开 C:\nginx\conf\nginx.conf 文件,添加或修改以下内容:

    server {
        listen       443 ssl;
        server_name  localhost;
    
        ssl_certificate      C:\nginx\conf\ssl\localhost.crt;
        ssl_certificate_key  C:\nginx\conf\ssl\localhost.key;
    
        location / {
            root   html;
            index  index.html index.htm;
        }
    }

4. 启动 Nginx

  • 打开命令提示符,进入 Nginx 安装目录:

    cd C:\nginx
  • 启动 Nginx:

    start nginx

5. 访问 HTTPS 站点

  • 打开浏览器,访问 https://localhost,浏览器可能会提示不安全,忽略警告继续访问。

案例

假设你有一个本地项目 C:\myproject,需要在 Nginx 上配置 SSL。

1. 配置 Nginx

修改 nginx.conf 文件:

server {
    listen       443 ssl;
    server_name  localhost;

    ssl_certificate      C:\nginx\conf\ssl\localhost.crt;
    ssl_certificate_key  C:\nginx\conf\ssl\localhost.key;

    location / {
        root   C:\myproject;
        index  index.html index.htm;
    }
}

2. 重启 Nginx

在命令提示符中执行:

nginx -s reload

3. 访问项目

打开浏览器,访问 https://localhost,即可看到 C:\myproject 中的内容。

注意事项

  • 自签名证书仅适用于本地测试,生产环境需使用受信任的 CA 签发的证书。

  • Nginx 默认监听 80 端口,如果端口被占用,需修改 nginx.conf 中的 listen 指令。

本篇文章内容来源于:windows Nginx 本地ssl详细说明以及案例