10.3 Nginx 安装

子章节
CentOS / RHEL(yum)
# 安装 EPEL 源
sudo yum install -y epel-release

# 安装 Nginx
sudo yum install -y nginx

# 启动并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx

# 检查运行状态
sudo systemctl status nginx

# 配置防火墙
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

Ubuntu / Debian(apt)
# 更新包索引
sudo apt update

# 安装 Nginx
sudo apt install -y nginx

# 启动并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx

# 检查运行状态
sudo systemctl status nginx

# 配置防火墙
sudo ufw allow 'Nginx Full'

源码编译安装
# 安装依赖
sudo yum install -y gcc-c++ pcre-devel zlib-devel make openssl-devel
# 或 Ubuntu
sudo apt install -y build-essential libpcre3-dev zlib1g-dev libssl-dev

# 下载源码
wget https://nginx.org/download/nginx-1.26.2.tar.gz
tar -xzf nginx-1.26.2.tar.gz
cd nginx-1.26.2

# 配置并编译
./configure --prefix=/usr/local/nginx --with-http_ssl_module
make
sudo make install

# 启动
sudo /usr/local/nginx/sbin/nginx

常用管理命令
# 管理 Nginx
sudo systemctl start nginx          # 启动
sudo systemctl stop nginx           # 停止
sudo systemctl restart nginx        # 重启
sudo systemctl reload nginx         # 重新加载配置(不中断服务)
sudo nginx -t                       # 测试配置文件语法
sudo nginx -s reload                # 重新加载配置

# 查看配置
cat /etc/nginx/nginx.conf # 主配置文件
ls /etc/nginx/conf.d/ # 子配置目录
ls /etc/nginx/sites-enabled/ # 站点配置(Ubuntu)

配置反向代理示例
server {
    listen 80;
    server_name example.com;

location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

HTTPS 配置示例(使用 Let's Encrypt)
# 安装 Certbot
sudo yum install -y certbot python3-certbot-nginx
# 或 Ubuntu
sudo apt install -y certbot python3-certbot-nginx

# 申请并自动配置 SSL 证书
sudo certbot --nginx -d example.com

# 证书自动续期
sudo certbot renew --dry-run