Nginx安装与基本配置
Nginx 支持多种安装方式,下面介绍主流操作系统的安装步骤与基础配置。
Linux 安装
Ubuntu/Debian
Bash
sudo apt update
sudo apt install nginx
CentOS/RHEL
Bash
sudo yum install epel-release
sudo yum install nginx
源码编译安装
Bash
# 安装依赖
sudo apt install build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev
# 下载源码
wget https://nginx.org/download/nginx-1.24.0.tar.gz
tar -zxvf nginx-1.24.0.tar.gz
cd nginx-1.24.0
# 编译安装
./configure --prefix=/etc/nginx --with-http_ssl_module
make
sudo make install
Windows 安装
Windows 不支持原生 Nginx,需下载预编译版本:
powershell
# 下载并解压
wget https://nginx.org/download/nginx-1.24.0.zip
Expand-Archive nginx-1.24.0.zip -DestinationPath C:\nginx
# 启动
cd C:\nginx
.\nginx.exe
macOS 安装
Bash
brew install nginx
验证安装
Bash
# 查看版本
nginx -v
# 查看编译参数
nginx -V
# 测试配置
nginx -t
# 启动服务
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
基本配置
主配置文件位置
| 系统 | 配置文件路径 |
|---|---|
| Ubuntu/Debian | /etc/nginx/nginx.conf |
| CentOS/RHEL | /etc/nginx/nginx.conf |
| macOS | /opt/homebrew/etc/nginx/nginx.conf |
| Windows | C:\nginx\conf\nginx.conf |
最小可用配置
nginx
worker_processes auto;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html;
}
}
}
注意事项
- 生产环境建议使用官方仓库安装,而非系统默认源(版本较旧)
- 源码编译安装需指定
--prefix安装路径- 修改配置后执行
nginx -t验证,避免配置错误导致服务无法启动- Windows 版本性能低于 Linux,不建议生产使用
目录结构
text
/etc/nginx/
├── nginx.conf # 主配置文件
├── mime.types # MIME 类型映射
├── conf.d/ # 额外配置目录
│ └── default.conf
├── sites-available/ # 可用站点配置(Debian)
├── sites-enabled/ # 已启用站点链接
├── ssl/ # 证书存放目录
└── fastcgi_params # FastCGI 参数
要点总结
- Linux 推荐使用包管理器安装,macOS 使用 Homebrew,Windows 使用预编译版
- 安装后主配置文件位于
/etc/nginx/nginx.conf - 修改配置前使用
nginx -t验证语法 - 启动服务使用
systemctl start nginx,设置开机自启使用enable - 生产环境建议从官方仓库获取最新版本
📝 发现内容有误?点击此处直接编辑