在 CentOS 上配置 Nginx 是一个常见的任务,Nginx 是一款轻量级、高性能的 HTTP 服务器和反向代理服务器,本文将详细介绍如何在 CentOS 上安装、配置和管理 Nginx,并提供一些常见问题的解答。
一、安装 Nginx
1. 通过 yum 命令安装 Nginx

这是最简单的安装方式,适用于大多数场景。
- 安装 Nginx
- yum y install nginx
- 启动 Nginx
- systemctl start nginx
- 设置开机自启
- systemctl enable nginx
2. 通过源码编译安装 Nginx
这种方式适用于需要自定义编译选项的场景。
- 安装依赖包
- yum y install gcc gccc++ make zlib zlibdevel openssl openssldevel pcre pcredevel
- 下载 Nginx 源码
- wget http://nginx.org/download/nginx1.24.0.tar.gz
- 解压源码包
- tar zxvf nginx1.24.0.tar.gz
- 编译并安装
- cd nginx1.24.0
- ./configure prefix=/usr/local/nginx
- make && make install
- 启动 Nginx
- /usr/local/nginx/sbin/nginx
二、配置 Nginx
1. 配置文件结构
Nginx 的配置文件通常位于/etc/nginx
或/usr/local/nginx/conf
目录下,主配置文件名为nginx.conf
,该文件包含全局配置和虚拟主机配置。
- /etc/nginx
- ├── conf.d
- │ └── default.conf
- ├── fastcgi.conf
- ├── fastcgi_params
- ├── mime.types
- ├── modulesenabled
- ├── modulesavailable
- ├── nginx.conf
- ├── scgi_params
- ├── uwsgi_params
- └── winutf
2. 基本配置示例

以下是一个基本的nginx.conf
配置示例:
- worker_processes 1;
- events {
- worker_connections 1024;
- }
- http {
- include mime.types;
- default_type application/octetstream;
- sendfile on;
- keepalive_timeout 65;
- server {
- listen 80;
- server_name example.com;
- location / {
- root /usr/share/nginx/html;
- index index.html index.htm;
- }
- }
- }
3. 虚拟主机配置
建议对虚拟主机的配置文件进行单独管理,以便新建和维护站点时更加方便,可以在/etc/nginx/vhost
目录下创建单独的配置文件:
- 进入配置目录
- cd /etc/nginx/
- 建立虚拟主机配置目录
- mkdir vhost
在vhost
目录中创建一个新的配置文件,如www.abc.com.conf
:
- server {
- listen 80;
- server_name www.abc.com abc.com;
- root /home/wwwroot/www.abc.com;
- index index.html index.htm;
- }
在主配置文件nginx.conf
中引入虚拟主机配置文件:
- include vhost/*.conf;
每次修改配置文件后,需重启 Nginx 使其生效:

- 重启 Nginx
- systemctl restart nginx
三、管理 Nginx
1. 常用管理命令
启动 Nginx:systemctl start nginx
停止 Nginx:systemctl stop nginx
重启 Nginx:systemctl restart nginx
重新加载配置文件:systemctl reload nginx
查看 Nginx 状态:systemctl status nginx
检查配置文件语法:nginx t
2. 防火墙配置
如果系统启用了防火墙,需要开放 HTTP(80)和 HTTPS(443)端口:
- 开放 HTTP 和 HTTPS 端口
- firewallcmd permanent addservice=http
- firewallcmd permanent addservice=https
- firewallcmd reload
四、常见问题与解答 (FAQs)
Q1: 如何更改 Nginx 默认监听的端口?
A1: 可以通过修改nginx.conf
中的listen
指令来更改默认监听端口,将默认的80端口改为8080:
- server {
- listen 8080;
- server_name example.com;
- ...
- }
然后重启 Nginx 使更改生效:systemctl restart nginx
。
Q2: Nginx 出现 “[emerg] getpwnam("nginx") failed” 错误怎么办?
A2: 这个错误通常是由于系统中没有名为nginx
的用户导致的,可以通过以下命令创建nginx
用户:
- useradd s /sbin/nologin M nginx
- id nginx # 确保用户已成功创建