Nginx 完整安装教程(Linux 主流系统 + 编译安装二选一)

一、CentOS / Rocky / RHEL (yum 快速安装)

1. 安装 epel 源

bash

运行

yum install -y epel-release

2. 安装 nginx

bash

运行

yum install -y nginx

3. 启停 & 开机自启

bash

运行

# 启动
systemctl start nginx
# 开机自启
systemctl enable nginx
# 停止
systemctl stop nginx
# 重载配置(不中断服务)
systemctl reload nginx
# 查看状态
systemctl status nginx

4. 防火墙放行 80/443

bash

运行

firewall-cmd --add-service=http --permanent
firewall-cmd --add-service=https --permanent
firewall-cmd --reload

5. 默认目录

  • 主配置:/etc/nginx/nginx.conf

  • 站点配置目录:/etc/nginx/conf.d/

  • 网页根目录:/usr/share/nginx/html

  • 日志:/var/log/nginx/

二、Ubuntu / Debian (apt 安装)

bash

运行

apt update
apt install -y nginx

管理命令同上 systemctl start nginx

配置路径:/etc/nginx/

三、源码编译安装(自定义模块,生产常用)

1. 安装依赖

bash

运行

# CentOS
yum install -y gcc gcc-c++ make zlib-devel pcre-devel openssl-devel wget

# Ubuntu
apt install -y gcc g++ make libz-dev libpcre3-dev libssl-dev wget

2. 下载稳定版 nginx(以 1.26.1 为例)

bash

运行

cd /usr/local/src
wget https://nginx.org/download/nginx-1.26.1.tar.gz
tar -zxvf nginx-1.26.1.tar.gz
cd nginx-1.26.1

3. 编译配置(基础 ssl+gzip)

bash

运行

./configure \
--prefix=/usr/local/nginx \
--with-http_gzip_module \
--with-http_ssl_module \
--with-http_stub_status_module

4. 编译安装

bash

运行

make && make install

5. 启停命令(源码无 systemd,直接二进制)

bash

运行

# 启动
/usr/local/nginx/sbin/nginx
# 停止
/usr/local/nginx/sbin/nginx -s stop
# 重载配置
/usr/local/nginx/sbin/nginx -s reload
# 测试配置是否报错
/usr/local/nginx/sbin/nginx -t

常用排错命令

  1. 校验配置文件语法

bash

运行

nginx -t
  1. 查看编译参数(源码安装)

bash

运行

nginx -V
  1. 查看版本

bash

运行