安装包:可自行前往我的飞书下载

也可以进入 nginx 官网,下载自己所需适应版本
开始安装nginx
1. 创建准备目录
cd /opt
mkdir soft module # 创建软件包和源码解压目录
2. 安装依赖环境
yum -y install make zlib zlib-devel gcc-c++ libtool openssl openssl-devel
3. 安装 PCRE(Nginx 依赖)
# 解压 PCRE
cd /opt/soft
tar -zxvf pcre-8.37.tar.gz -C ../module/
# 编译安装
cd /opt/module/pcre-8.37
./configure --prefix=/usr/local/pcre8
make && make install
4. 安装 Nginx
# 解压 Nginx
cd /opt/soft
tar -zxvf nginx-1.20.2.tar.gz -C ../module/
# 配置编译选项
cd /opt/module/nginx-1.20.2
./configure --prefix=/usr/local/nginx
# 编译并安装
make && make install
5. 验证安装
# 检查版本
/usr/local/nginx/sbin/nginx -v
# 测试配置文件
/usr/local/nginx/sbin/nginx -t

6. 启动 Nginx
/usr/local/nginx/sbin/nginx
# 检查进程(要有master和worker)
ps -ef | grep nginx
# 测试访问
curl http://localhost


静态站点部署
1.创建站点目录和文件
# 进入Nginx的HTML目录
cd /usr/local/nginx/html
# 创建hello子目录
mkdir hello
# 创建hello.html文件(使用vim或直接echo)
cat > hello/hello.html <<EOF
<html>
<header>
<title>hello</title>
</header>
<body>
<h1>Hello Nginx</h1>
</body>
</html>
EOF

2.修改Nginx配置文件
vim /usr/local/nginx/conf/nginx.conf
在http块内添加server配置:
nginx
server {
listen 10010;
location / {
root html/hello;
index hello.html;
}
}
3.检查并启动
# 测试配置文件语法
/usr/local/nginx/sbin/nginx -t
# 重启Nginx(如果已运行)
/usr/local/nginx/sbin/nginx -s reload
# 首次启动(如果未运行)
/usr/local/nginx/sbin/nginx
4.访问测试
# 检查端口监听
netstat -tulnp | grep 10010
# 测试访问(本地)
curl http://localhost:10010
# 或浏览器访问
echo "访问地址:http://服务器IP:10010"

5.防火墙设置(如需)
# 开放10010端口
firewall-cmd --add-port=10010/tcp --permanent
firewall-cmd --reload
# 或iptables
iptables -I INPUT -p tcp --dport 10010 -j ACCEPT
service iptables save
关键点说明
-
路径关系:
-
配置文件中的
root html/hello
实际指向/usr/local/nginx/html/hello/
-
必须确保hello.html位于该目录
-
-
权限问题:
chown -R nobody:nobody /usr/local/nginx/html/hello chmod -R 755 /usr/local/nginx/html/hello
-
备选配置方案:
nginx
server { listen 10010; root /usr/local/nginx/html/hello; index hello.html; location / { try_files $uri $uri/ =404; } }
遇到问题时可通过查看错误日志排查:
tail -f /usr/local/nginx/logs/error.log
常见问题处理
1. 端口冲突(80 端口被占用)
netstat -tulnp | grep 80 # 查看占用进程
systemctl stop httpd # 停止 Apache(示例)
2. 启动失败(缺少 pid 文件)
# 强制停止残留进程
killall nginx
# 重新启动
/usr/local/nginx/sbin/nginx
3. 重新加载配置
/usr/local/nginx/sbin/nginx -s reload
卸载方法
# 停止服务
/usr/local/nginx/sbin/nginx -s stop
# 删除文件
rm -rf /usr/local/nginx /usr/local/pcre8