在 Linux 系统中安装 Nginx 的步骤如下,根据不同的发行版选择对应的命令:
# 更新软件包列表
sudo apt update
# 安装 Nginx
sudo apt install nginx
# 启动 Nginx
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
# 添加 EPEL 仓库(如果需要)
sudo dnf install epel-release
# 安装 Nginx
sudo dnf install nginx
# 启动并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx
# 添加 EPEL 仓库
sudo yum install epel-release
# 安装 Nginx
sudo yum install nginx
# 启动并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx
# 安装 Nginx
sudo dnf install nginx
# 启动并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx
# 安装 Nginx
sudo pacman -S nginx
# 启动并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx
安装完成后,可以通过以下命令检查 Nginx 是否正常运行:
systemctl status nginx
或访问服务器的 IP 地址(http://你的服务器IP
),如果看到 Nginx 的欢迎页面,说明安装成功。
防火墙配置:如果系统启用了防火墙(如 ufw
或 firewalld
),需放行 HTTP(80)和 HTTPS(443)端口:
# Ubuntu/Debian (ufw)
sudo ufw allow 'Nginx Full'
# RHEL/CentOS (firewalld)
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
配置文件路径:Nginx 的默认配置文件通常位于 /etc/nginx/nginx.conf
,站点配置通常在 /etc/nginx/conf.d/
或 /etc/nginx/sites-available/
。
如果需要最新版本或自定义模块,可以从源码编译:
# 下载源码(替换为最新版本号)
wget http://nginx.org/download/nginx-1.25.3.tar.gz
tar -xzvf nginx-1.25.3.tar.gz
cd nginx-1.25.3
# 编译安装(需提前安装 gcc、make 等工具)
./configure
make
sudo make install
# 启动 Nginx(默认安装路径为 /usr/local/nginx)
/usr/local/nginx/sbin/nginx
根据你的 Linux 发行版选择对应的命令即可完成安装!如果有其他问题(如端口冲突、权限错误等),可以进一步排查日志(/var/log/nginx/error.log
)。