在CentOS系统中启动Nginx是一项常见任务,无论是用于开发、测试还是生产环境,本文将详细讲解如何在CentOS上启动Nginx,包括安装、配置、启动和停止命令等各个方面。
一、安装Nginx
1. 使用YUM安装Nginx

sudo yum install epelrelease sudo yum install nginx
2. 使用源码包安装Nginx
如果需要特定版本的Nginx或者需要自定义编译选项,可以使用源码包进行安装。
下载Nginx源码包
wget http://nginx.org/download/nginx1.9.8.tar.gz
解压源码包
tar zxvf nginx1.9.8.tar.gz
进入解压后的目录
cd nginx1.9.8
配置、编译并安装Nginx
./configure prefix=/usr/local/nginx \
sbinpath=/usr/sbin/nginx \
confpath=/etc/nginx/nginx.conf \
errorlogpath=/var/log/nginx/error.log \
httplogpath=/var/log/nginx/access.log \
pidpath=/var/run/nginx.pid \
lockpath=/var/run/nginx.lock \
httpclientbodytemppath=/var/tmp/nginx/client \
httpproxytemppath=/var/tmp/nginx/proxy \
httpfastcgitemppath=/var/tmp/nginx/fcgi \
httpuwsgitemppath=/var/tmp/nginx/uwsgi \
httpscgitemppath=/var/tmp/nginx/scgi \
user=nginx \
group=nginx \
withpcre \
withhttp_v2_module \
withhttp_ssl_module \
withhttp_realip_module \
withhttp_addition_module \
withhttp_sub_module \
withhttp_dav_module \
withhttp_flv_module \
withhttp_mp4_module \
withhttp_gunzip_module \
withhttp_gzip_static_module \
withhttp_random_index_module \
withhttp_secure_link_module \
withhttp_auth_request_module \
withmail \
withmail_ssl_module \
withfileaio \
withipv6 \
withhttp_v2_module \
withthreads \
withstream \
withstream_ssl_module
make
sudo make install二、启动Nginx
使用Systemctl启动Nginx
sudo systemctl start nginx
使用Nginx命令行工具启动Nginx
/usr/local/nginx/sbin/nginx c /etc/nginx/nginx.conf
三、验证Nginx是否启动成功
可以通过以下命令查看Nginx的运行状态:
ps ef | grep nginx
如果能看到两个相邻ID的进程,说明Nginx已经成功启动,还可以通过访问服务器的IP地址或域名来检查Nginx是否正常运行,

http://服务器的IP:80
四、停止Nginx服务
平滑关闭Nginx服务
nginx s quit
立即停止Nginx服务
sudo systemctl stop nginx
五、重启Nginx服务
sudo systemctl restart nginx
六、设置开机自启动Nginx服务
sudo systemctl enable nginx
七、常见问题及解决方法
问题1:无法找到Nginx命令
如果系统提示找不到Nginx命令,可能是Nginx没有正确安装或者路径未添加到环境变量中,可以通过以下命令添加Nginx到系统路径:
export PATH=$PATH:/usr/local/nginx/sbin
问题2:80端口被占用
如果Nginx启动失败并提示80端口被占用,可以使用以下命令查找占用80端口的进程:

netstat ano | grep 80
根据查找结果,可以选择停止占用80端口的服务或者修改Nginx配置文件中的端口号。
八、FAQs问答环节
Q1:如何更改Nginx默认Web根目录?
A1:要更改Nginx的默认Web根目录,可以编辑Nginx的主配置文件nginx.conf,通常位于/etc/nginx/nginx.conf或/usr/local/nginx/conf/nginx.conf,找到root指令并修改其值为新的目录路径。
server {
listen 80;
server_name localhost;
root /new/web/root; # 修改为新的根目录路径
index index.html index.htm;
}修改完成后,重新加载Nginx配置以使更改生效:
sudo systemctl reload nginx
Q2:如何配置Nginx支持HTTPS?
A2:要配置Nginx支持HTTPS,需要在Nginx配置文件中添加SSL证书和密钥文件的路径,以下是一个简单的HTTPS配置示例:
server {
listen 443 ssl; # 监听443端口并启用SSL
server_name example.com; # 替换为你的域名
ssl_certificate /path/to/your/fullchain.pem; # SSL证书路径
ssl_certificate_key /path/to/your/privkey.pem; # SSL私钥路径
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # 启用的SSL协议版本
ssl_ciphers HIGH:!aNULL:!MD5; # 启用的加密套件
location / {
root /usr/share/nginx/html; # Web根目录
index index.html index.htm; # 索引文件
}
}
```配置完成后,同样需要重新加载Nginx配置:sudo systemctl reload nginx
```你需要确保SSL证书和密钥文件存在且路径正确,你可以使用Let's Encrypt等免费证书颁发机构获取SSL证书。
