本文详细介绍在 CentOS 6/7/8 系统上安装和配置 Nginx Web 服务器的方法,包括从官方源安装、基础配置、常见问题解决和性能优化建议。

什么是 Nginx:

Nginx(发音为"engine-x")是一个高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3/SMTP 代理服务器。由俄罗斯程序员 Igor Sysoev 开发,以其稳定性、丰富的功能集、简单的配置和低资源消耗而闻名。

Nginx 的主要优势:

  • 高性能和低内存占用
  • 支持高并发连接(C10K 问题的解决方案)
  • 反向代理和负载均衡
  • 静态文件服务优秀
  • 灵活的配置系统
  • 热部署和不间断升级

应用场景:

  • Web 服务器(静态网站托管)
  • 反向代理服务器
  • 负载均衡器
  • HTTP 缓存服务器
  • API 网关

无论您使用的是香港独立服务器新加坡VPS还是其他地区的服务器,Nginx 都是构建高性能 Web 服务的首选方案。


系统要求:

适用系统版本:

  • CentOS 6.x
  • CentOS 7.x
  • CentOS 8.x / Rocky Linux 8 / AlmaLinux 8
  • RHEL 6/7/8

最低硬件要求:

  • CPU:1 核心
  • 内存:512MB(建议 1GB 以上)
  • 磁盘:至少 1GB 可用空间
  • 网络:稳定的互联网连接

权限要求:

  • root 或 sudo 权限

方法一:从 Nginx 官方源安装(推荐)

使用 Nginx 官方源可以获得最新稳定版本,并享受官方支持。这是推荐的安装方法,特别适合运行在日本独立服务器韩国VPS等生产环境的服务器。

第一步:创建 Nginx 官方 Yum 源

SSH 登录服务器后,创建源配置文件:

vi /etc/yum.repos.d/nginx.repo

输入以下内容:

[nginx] name=nginx repo baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/ gpgcheck=0 enabled=1

或者使用稳定版(推荐生产环境):

[nginx-stable] name=nginx stable repo baseurl=http://nginx.org/packages/centos/$releasever/$basearch/ gpgcheck=1 enabled=1 gpgkey=https://nginx.org/keys/nginx_signing.key module_hotfixes=true

配置说明:

  • name - 源的名称
  • baseurl - 软件包下载地址
    • mainline - 最新开发版(包含最新特性)
    • stable - 稳定版(推荐生产环境)
  • $releasever - 自动替换为系统版本号(6、7、8)
  • $basearch - 自动替换为系统架构(x86_64)
  • gpgcheck - 是否检查 GPG 签名(1 启用,0 禁用)
  • enabled - 是否启用该源(1 启用,0 禁用)

针对不同 CentOS 版本的配置:

CentOS 6:

[nginx] name=nginx repo baseurl=http://nginx.org/packages/centos/6/$basearch/ gpgcheck=0 enabled=1

CentOS 7:

[nginx] name=nginx repo baseurl=http://nginx.org/packages/centos/7/$basearch/ gpgcheck=0 enabled=1

CentOS 8 / Rocky Linux 8:

[nginx] name=nginx repo baseurl=http://nginx.org/packages/centos/8/$basearch/ gpgcheck=0 enabled=1 module_hotfixes=true

注意: module_hotfixes=true 对于 CentOS 8 很重要,用于解决模块化冲突。

保存文件并退出(vi 编辑器按 Esc,输入 :wq 回车)。

第二步:安装 Nginx

清理 Yum 缓存:

yum clean all yum makecache

安装 Nginx:

yum install nginx -y

安装过程说明:

执行命令后,系统会自动下载并安装 Nginx 及其依赖包。安装过程中会显示详细信息,最后出现 "Complete!" 表示安装成功。

验证安装:

检查 Nginx 版本:

nginx -v

输出示例:

nginx version: nginx/1.24.0

查看详细信息:

nginx -V

这会显示编译参数和模块信息。

第三步:启动 Nginx 服务

CentOS 6 系统:

service nginx start

设置开机自启动:

chkconfig nginx on

查看服务状态:

service nginx status

CentOS 7/8 系统:

启动服务:

systemctl start nginx

设置开机自启动:

systemctl enable nginx

查看服务状态:

systemctl status nginx

输出示例:

● nginx.service - nginx - high performance web server Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled) Active: active (running) since Wed 2025-12-18 10:00:00 CST; 5min ago Main PID: 1234 (nginx) CGroup: /system.slice/nginx.service ├─1234 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf └─1235 nginx: worker process

常用服务管理命令:

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

第四步:测试 Nginx 运行

本地测试:

curl http://localhost

wget -O - http://localhost

如果看到 Nginx 默认欢迎页面的 HTML 代码,说明安装成功。

检查进程:

ps aux | grep nginx

输出示例:

root 1234 0.0 0.1 46384 1940 ? Ss 10:00 0:00 nginx: master process nginx 1235 0.0 0.2 46880 2560 ? S 10:00 0:00 nginx: worker process

检查端口监听:

netstat -tunlp | grep 80

ss -tunlp | grep 80

输出示例:

tcp LISTEN 0 128 *:80 : users:(("nginx",pid=1235,fd=6))


Nginx 目录结构

了解 Nginx 的目录结构对于配置和管理至关重要。

查找 Nginx 安装位置:

whereis nginx

输出示例:

nginx: /usr/sbin/nginx /etc/nginx /usr/share/nginx /usr/share/man/man8/nginx.8.gz

主要目录和文件:

1. 主程序:

/usr/sbin/nginx

2. 配置文件目录:

/etc/nginx/

主要配置文件:

  • /etc/nginx/nginx.conf - 主配置文件
  • /etc/nginx/conf.d/ - 虚拟主机配置目录
  • /etc/nginx/default.d/ - 默认配置目录

3. 网站根目录:

/usr/share/nginx/html/

默认首页:/usr/share/nginx/html/index.html

4. 日志目录:

/var/log/nginx/

  • /var/log/nginx/access.log - 访问日志
  • /var/log/nginx/error.log - 错误日志

5. PID 文件:

/var/run/nginx.pid

6. 模块目录:

/usr/lib64/nginx/modules/

查看目录权限:

ls -la /etc/nginx/ ls -la /usr/share/nginx/html/ ls -la /var/log/nginx/


常用 Nginx 命令

1. 启动 Nginx:

nginx

systemctl start nginx

2. 停止 Nginx:

优雅停止(等待请求处理完成):

nginx -s quit

快速停止:

nginx -s stop

killall nginx

使用信号停止:

kill -QUIT $(cat /var/run/nginx.pid)

3. 重启 Nginx:

重启服务(会中断连接):

systemctl restart nginx

service nginx restart

4. 重载配置(不中断服务,推荐):

nginx -s reload

systemctl reload nginx

killall -HUP nginx

或使用信号:

kill -HUP $(cat /var/run/nginx.pid)

5. 测试配置文件:

在修改配置后重载前,务必先测试配置是否正确:

nginx -t

输出示例(配置正确):

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful

输出示例(配置错误):

nginx: [emerg] unexpected ";" in /etc/nginx/nginx.conf:25 nginx: configuration file /etc/nginx/nginx.conf test failed

6. 查看版本和编译信息:

nginx -v # 简单版本信息 nginx -V # 详细版本和编译参数

7. 查看帮助:

nginx -h

8. 指定配置文件启动:

nginx -c /path/to/nginx.conf

9. 查看 Nginx 进程:

ps aux | grep nginx

10. 查看端口占用:

lsof -i :80 netstat -tunlp | grep :80 ss -tunlp | grep :80


解决外网无法访问问题

这是新安装 Nginx 最常见的问题。如果在服务器本地可以访问(curl localhost 正常),但从外网或局域网其他机器无法访问,通常是防火墙问题。特别是在台湾独立服务器马来西亚VPS等云服务器上,需要同时配置系统防火墙和云平台安全组。

问题现象:

本地测试正常:

curl http://localhost

能看到 Nginx 欢迎页面。

外网测试失败:

从其他机器访问:

wget http://192.168.0.100

提示:

Connecting to 192.168.0.100:80... failed: No route to host.

或使用 telnet 测试:

telnet 192.168.0.100 80

提示:

正在连接到192.168.0.100...不能打开到主机的连接,在端口 80: 连接失败

原因分析:

这是因为 CentOS 默认启用了 iptables 防火墙,并且没有开放 80 端口。


解决方法:配置防火墙

方案一:临时开放端口(CentOS 6)

临时添加规则(重启后失效):

iptables -I INPUT -p tcp --dport 80 -j ACCEPT

参数说明:

  • -I INPUT - 在 INPUT 链的最前面插入规则
  • -p tcp - 协议为 TCP
  • --dport 80 - 目标端口为 80
  • -j ACCEPT - 动作为接受

查看防火墙规则:

iptables -L -n

/etc/init.d/iptables status

应该能看到类似这样的规则:

ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:80

永久保存规则:

service iptables save

iptables-save > /etc/sysconfig/iptables

方案二:使用 Firewalld(CentOS 7/8)

CentOS 7 及更高版本默认使用 firewalld 替代 iptables。

检查 firewalld 状态:

systemctl status firewalld

开放 HTTP 端口(80):

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

或直接指定端口号:

firewall-cmd --permanent --add-port=80/tcp

开放 HTTPS 端口(443):

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

firewall-cmd --permanent --add-port=443/tcp

重载防火墙配置:

firewall-cmd --reload

查看已开放的端口:

firewall-cmd --list-all

输出示例:

public (active) target: default icmp-block-inversion: no interfaces: eth0 sources: services: dhcpv6-client http https ssh ports: protocols: masquerade: no forward-ports: source-ports: icmp-blocks: rich rules:

查看已开放的服务:

firewall-cmd --list-services

查看已开放的端口:

firewall-cmd --list-ports

删除规则(如果需要):

firewall-cmd --permanent --remove-service=http firewall-cmd --permanent --remove-port=80/tcp firewall-cmd --reload

方案三:配置云服务器安全组

如果使用云服务器(如阿里云、腾讯云、AWS、Azure 等),除了系统防火墙,还需要在云平台控制台配置安全组规则。

基本步骤(各平台类似):

  1. 登录云服务器控制台
  2. 找到"安全组"或"防火墙规则"设置
  3. 添加入站规则:
    • 协议:TCP
    • 端口:80(HTTP)和 443(HTTPS)
    • 来源:0.0.0.0/0(所有 IP)或指定 IP 段
  4. 保存并应用规则

安全建议:

对于生产环境,建议限制访问来源:

  • 仅开放必要的端口
  • 使用 IP 白名单限制管理端口(如 SSH 22 端口)
  • HTTP 和 HTTPS 端口可以对公网开放
  • 数据库端口(3306、5432 等)不要对公网开放

基础配置优化

主配置文件结构:

Nginx 主配置文件位于 /etc/nginx/nginx.conf。

查看默认配置:

cat /etc/nginx/nginx.conf

典型配置示例:

user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid;

events { worker_connections 1024; }

http { log_format main 'remote_addr - $remote_user [time_local] "$request" ' 'status $body_bytes_sent "http_referer" ' '"httpuseragent""http_x_forwarded_for"';

access_log /var/log/nginx/access.log main;

sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;

include /etc/nginx/mime.types;
default_type application/octet-stream;

include /etc/nginx/conf.d/*.conf;

}

配置虚拟主机:

在 /etc/nginx/conf.d/ 目录下创建虚拟主机配置文件:

vi /etc/nginx/conf.d/example.com.conf

简单的虚拟主机配置:

server { listen 80; server_name example.com www.example.com; root /var/www/example.com; index index.html index.htm;

access_log /var/log/nginx/example.com.access.log main;
error_log /var/log/nginx/example.com.error.log;

location / {
 try_files $uri $uri/ =404;
}

error_page 404 /404.html;
location = /404.html {
 internal;
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
 internal;
}

}

创建网站目录:

mkdir -p /var/www/example.com echo "

Welcome to Example.com

" > /var/www/example.com/index.html chown -R nginx:nginx /var/www/example.com

 

测试并重载配置:

nginx -t nginx -s reload


性能优化建议

1. 调整 worker 进程数:

worker_processes auto;

或根据 CPU 核心数手动设置:

worker_processes 4;

2. 增加连接数:

events { worker_connections 2048; use epoll; }

3. 启用 Gzip 压缩:

http { gzip on; gzip_vary on; gzip_min_length 1024; gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml+rss application/json; }

4. 缓存静态文件:

location ~* .(jpg|jpeg|png|gif|ico|css|js)$ { expires 30d; add_header Cache-Control "public, immutable"; }

5. 限制请求速率:

http { limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;

server {
 location / {
 limit_req zone=one burst=5;
 }
}

}


常见问题排查

问题 1:Nginx 无法启动

  • 查看错误日志: tail -f /var/log/nginx/error.log
  • 检查配置: nginx -t
  • 检查端口占用: netstat -tunlp | grep :80

问题 2:403 Forbidden

  • 检查文件权限: ls -la /usr/share/nginx/html/
  • 检查 SELinux: getenforce
  • 临时禁用: setenforce 0

问题 3:502 Bad Gateway

  • 检查后端服务: 确认 PHP-FPM 或其他后端服务正在运行
  • 检查 upstream 配置

问题 4:配置修改不生效

  • 测试配置: nginx -t
  • 重载配置: nginx -s reload
  • 清除缓存: 浏览器清除缓存

通过以上详细的安装和配置步骤,您可以在 CentOS 系统上成功部署 Nginx Web 服务器。从官方源安装可以获得最新稳定版本和持续更新支持。合理的配置和优化能够充分发挥 Nginx 的高性能优势,为您的网站或应用提供稳定可靠的服务。