在Linux系统中安装Nginx可以通过包管理器或源码编译两种方式。以下是详细步骤(以常见发行版为例):
# 更新软件包列表
sudo apt update
# 安装Nginx
sudo apt install nginx
# 启动Nginx
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
# 添加EPEL仓库(CentOS/RHEL 7/8)
sudo yum install epel-release
# 安装Nginx
sudo yum install nginx
# 启动并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx
sudo dnf install nginx
sudo systemctl start nginx
sudo systemctl enable nginx
wget https://nginx.org/download/nginx-1.25.3.tar.gz
tar -zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.3
# Debian/Ubuntu
sudo apt install build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev
# CentOS/RHEL
sudo yum install gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel
./configure --prefix=/usr/local/nginx \ # 安装路径
--with-http_ssl_module \ # 启用SSL模块
--with-http_v2_module # 启用HTTP/2
make && sudo make install
# 进入安装目录
cd /usr/local/nginx/sbin
# 启动
sudo ./nginx
# 验证
curl http://localhost
检查服务状态:
systemctl status nginx # 包管理器安装
ps aux | grep nginx # 源码安装检查进程
访问默认页面:
http://<服务器IP>
bash
curl http://localhost
# Ubuntu/Debian (ufw)
sudo ufw allow 'Nginx Full' # 或单独放行80/443端口
# CentOS/RHEL (firewalld)
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
/etc/nginx/
(包安装)或 /usr/local/nginx/conf/
(源码安装)/usr/share/nginx/html/
或 /var/www/html
/var/log/nginx/
/etc/nginx/nginx.conf
中的 listen
指令。www-data
或 nginx
)对网站目录有读取权限。nginx -V
查看已编译模块,需重新编译添加缺失模块。通过上述步骤,您可以在主流Linux发行版上完成Nginx的安装。包管理器适合快速部署,源码编译适合需要定制功能的场景。