背景
为了练习管理服务器,我打算在自己的电脑上模拟一个企业级内部环境。通过调整 hosts 文件或者内部 DNS 服务器设置,我希望能够使用内部域名访问服务器,而且要求使用 HTTPS 进行访问。为此,我选择在 Windows11 上安装 WSL2,并在 WSL2 中编译安装 Nginx,以实现最大程度的自定义配置。
环境
- 操作系统:Windows 11 23H2
- 终端:PowerShell 5.1
准备工作
1. 安装 wsl
参考 WSL 官方文档 从零开始:Windows 11 安装使用 WSL
2. 安装编译工具
1
| apt update && apt install build-essential zlib1g zlib1g-dev libgd-dev libgdal-dev libpcre3 libpcre3-dev -y
|
有位不知名大佬推荐安装两遍编译工具,使最后显示 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
,这样做是为了避免在编译和安装过程中出现由于依赖项未满足导致的错误。(有人知道出处的话请联系我更新)
3. 更新 openssl 版本(可选)
来自 openssl 官网:All older versions (including 1.1.1, 1.1.0, 1.0.2, 1.0.0 and 0.9.8) are now out of support and should not be used. Users of these older versions are encouraged to upgrade to 3.2 or 3.0 as soon as possible. 所有旧版本(包括 1.1.1、1.1.0、1.0.2、1.0.0 和 0.9.8)现在都不再支持,不应再使用。使用这些旧版本的用户应尽快升级到 3.2 或 3.0。
1
| ./config --prefix=`[path]`
|
1
| make -j $(nproc) && make install -j $(nproc)
|
1
2
| ln -s `[path]`/bin/openssl /usr/bin/openssl
ln -s `[path]`/include/openssl /usr/include/openssl
|
1
| echo "[path]/lib64" >> /etc/ld.so.conf
|
编译安装 Nginx
以下使用 /usr/local/src/
存放源代码,使用 /usr/local/nginx
存放安装路径
- 创建一个 nginx 用户,为了降低服务器风险,让 nginx 以最小的权限运行
1
| useradd -s /sbin/nologin nginx # 删除用户及其用户目录 userdel -r username
|
查看所有登录 shell 不为 / sbin/nologin 或 / bin/false 用户:grep -vE ‘/sbin/nologin|/bin/false’ /etc/passwd
1
| wget https://nginx.org/download/nginx-x.x.x.tar.gz # x.x.x 为具体的版本号
|
1
| tar -xzf nginx-x.x.x.tar.gz # x 表示提取 z 表示使用 gzip(通常用户. tar.gz 或. tgz 文件) f 表示指定要操作的文件 v 可选:表示显示详细的操作信息
|
1
| ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module #设置安装路径 设置用户 设置用户组 添加 https 支持
|
1
| make -j$(nproc) && make install -j$(nproc) # 自动最大线程编译安装
|
1
2
3
4
| cd /usr/local/nginx/sbin && ./nginx #启动
./nginx -t # 验证配置文件
./nginx -v # 查看版本
curl http://localhost # 访问默认页面,启动成功会回显 nginx 欢迎页面的 html 响应
|
其他配置
- 使用软链接将 nginx 添加到系统的可执行路径中
1
| ln -s /usr/local/nginx/sbin/nginx /usr/bin/nginx
|
- 编写 / usr/lib/systemd/system/nginx.service,使用 systemctl 管理 nginx
参考 systemd 官网,man 手册 (man systemd.unit)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| [Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true
[Install]
WantedBy=multi-user.target
|
验证 nginx 是否正常运行:
1
| systemctl daemon-reload && systemctl stop nginx.service && systemctl start nginx.service && systemctl reload nginx.service && systemctl restart nginx.service && systemctl status nginx # 应显示 Active: active (running) 开机自启(可选):systemctl enable nginx
|
配置 HTTPS 访问