Nginx 在各平台的详细安装步骤

177 阅读3分钟

以下是在各主流平台上安装 Nginx 的详细步骤,包括 Linux(Ubuntu/Debian/CentOS)、macOS 和 Windows 的安装方法:

一、Linux 系统安装 Nginx

1. Ubuntu/Debian

# 1. 更新软件包列表
sudo apt update
​
# 2. 安装 Nginx
sudo apt install nginx -y
​
# 3. 启动 Nginx
sudo systemctl start nginx
​
# 4. 设置开机自启
sudo systemctl enable nginx
​
# 5. 检查状态
sudo systemctl status nginx
​
# 6. 验证(默认监听80端口)
curl http://localhost
或者通过访问服务器的 IP 地址或域名,应该能看到 Nginx 的默认欢迎页面。
  • 默认配置文件路径:/etc/nginx/nginx.conf
  • 站点配置文件路径:/etc/nginx/sites-available/
  • 默认网页目录:/var/www/html

2. CentOS/RHEL

# 1. 添加 EPEL 仓库(CentOS 7/8)
sudo yum install epel-release -y
​
# 2. 安装 Nginx
sudo yum install nginx -y
​
# 3. 启动并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx
​
# 4. 检查状态
sudo systemctl status nginx
​
# 5. 开放防火墙(如果需要)
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
  • 配置文件路径:/etc/nginx/nginx.conf

二、macOS 安装 Nginx

1:Homebrew 安装(推荐)

# 1. 安装 Homebrew(如果未安装)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"# 2. 安装 Nginx
brew install nginx
​
# 3. 启动 Nginx
brew services start nginx  # 后台运行
# 或手动运行:
nginx
​
# 4. 验证
curl http://localhost:8080  # 默认端口8080(Mac 防止与系统冲突)
  • 配置文件路径:/usr/local/etc/nginx/nginx.conf
  • 默认网页目录:/usr/local/var/www

2:MacPorts 安装

sudo port install nginx

三、Windows 安装 Nginx

1. 手动安装

步骤:

  1. 下载 Nginx

  2. 解压到本地目录

    • 例如解压到 C:\nginx
  3. 启动 Nginx

    • 打开 命令提示符(管理员) ,运行:

      cd C:\nginx
      start nginx
      
    • 或直接双击 nginx.exe

  4. 验证

    • 浏览器访问 http://localhost,看到欢迎页即成功。
  5. 停止 Nginx

    nginx -s stop       # 快速停止
    nginx -s quit       # 优雅停止
    nginx -s reload     # 重新加载配置
    

2. Chocolatey 安装

# 1. 安装 Chocolatey(如果尚未安装)
#以管理员身份打开 PowerShell,并执行以下命令安装 Chocolatey:
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
​
# 2. 安装 Nginx
choco install nginx
​
# 3. 启动 Nginx
start nginx
#或者直接双击 `nginx.exe` 文件启动# 4. 验证
curl http://localhost  # 默认监听80端口

四、验证安装

  • Linux/macOS

    curl -I http://localhost
    

    输出应包含 HTTP/1.1 200 OK

  • Windows: 浏览器访问 http://localhost,显示 Nginx 欢迎页。


五、常见问题

  1. 端口冲突

    • 如果 80 端口被占用(如 Apache、IIS),修改 nginx.conf 中的 listen 端口。

    • 检查端口占用:

      sudo netstat -tulnp | grep 80  # Linux
      netstat -ano | findstr :80     # Windows
      
  2. 权限问题

    • Linux 下若绑定 80 端口需 root 权限,或使用 sudo nginx
  3. 防火墙拦截

    • 确保放行 HTTP(80)/HTTPS(443)端口。

六、卸载 Nginx

  • Ubuntu/Debian

    sudo apt purge nginx nginx-common -y
    sudo rm -rf /etc/nginx /var/www/html
    
  • CentOS

    sudo yum remove nginx
    
  • macOS

    brew uninstall nginx
    
  • Windows: 直接删除解压的 Nginx 目录即可。


通过以上步骤,你可以在各平台成功安装并运行 Nginx。如果需要配置虚拟主机或 HTTPS,可进一步修改 nginx.conf 或站点配置文件。