发布作者: 大鱼
百度收录: 正在检测是否收录...
作品采用: 《 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 》许可协议授权
nginx 是目前使用最广的 Web 服务器与反向代理,三个系统的安装方式各不相同,但配置文件的格式完全一致,学会一套就能通用。本文只讲三件事:怎么装、配置文件在哪怎么编辑、开机怎么自启。装好之后,所有站点配置都写在同一个主配置文件里,改完做一次语法检查再让它重新加载即可。文中的路径均以各系统默认安装位置为准,若你改过解压目录或安装前缀,按实际情况替换。看完这一篇,你就能在任意一台机器上把 nginx 跑起来并加入开机启动。多站点、HTTPS、负载均衡等进阶内容本文不涉及。
安装
# Debian / Ubuntu
sudo apt update && sudo apt install -y nginx
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y nginx配置文件位置
/etc/nginx/nginx.conf/etc/nginx/sites-available/(启用需软链到 sites-enabled/);RHEL 系在 /etc/nginx/conf.d/,*.conf 自动加载编辑
sudo vim /etc/nginx/nginx.conf # 或用 nano /etc/nginx/nginx.conf
sudo nginx -t # 改完先检查语法
sudo systemctl reload nginx # 语法通过再平滑重载开机自启
sudo systemctl enable nginx # 注册开机自启(当前会话也会启动)
sudo systemctl disable nginx # 取消开机自启安装
nginx 官方不提供 Windows 安装包,只有压缩包。到 https://nginx.org/en/download.html 下载 nginx/Windows-1.xx.x,解压到不含中文和空格的短路径,例如 C:\nginx。
配置文件位置
C:\nginx\conf\nginx.confC:\nginx\logs\编辑
用记事本或 VS Code 直接打开 C:\nginx\conf\nginx.conf 修改。改完在 nginx 目录内执行:
cd C:\nginx
nginx -t
nginx -s reload开机自启
nginx 自身不能注册为服务,用 nssm 包一层:
nssm install nginx "C:\nginx\nginx.exe"
nssm set nginx AppDirectory "C:\nginx"
nssm set nginx Start SERVICE_AUTO_START
nssm start nginx安装
brew install nginx配置文件位置
/opt/homebrew/etc/nginx/nginx.conf/usr/local/etc/nginx/nginx.conf编辑
open -e /opt/homebrew/etc/nginx/nginx.conf # 用文本编辑器打开
# 或 vim /opt/homebrew/etc/nginx/nginx.conf
nginx -t && nginx -s reload开机自启
brew services 由 launchd 托管,启动即等于注册开机自启:
brew services start nginx # 启动并设为开机自启
brew services list # 查看状态
brew services stop nginx # 停止并取消自启注意:Homebrew 默认监听 8080 端口(非 root 无权绑定 80),访问地址是 http://localhost:8080。
| 系统 | 配置文件 | 自启方式 |
|---|---|---|
| Linux | /etc/nginx/nginx.conf | systemctl enable nginx |
| Windows | C:\nginx\conf\nginx.conf | nssm set nginx Start SERVICE_AUTO_START |
| macOS | /opt/homebrew/etc/nginx/nginx.conf | brew services start nginx |
—— 评论区 ——