CentOS 7 安装 Nginx 及开机启动配置步骤
首先前往 Nginx 官方网站获取安装包。
访问 http://nginx.org/en/download.html,挑选适用于 Linux 系统的版本。建议选用最新版本,下载至本地后上传至服务器,或在 CentOS 环境中直接使用 wget 命令进行下载。

进入 /usr/local 目录准备下载软件包。
# cd /usr/local
# wget http://nginx.org/download/nginx-1.11.5.tar.gz
接下来执行 Nginx 的安装操作。
在安装前需先运行相关命令以安装 Nginx 所需的依赖库。若缺失必要依赖,可能导致安装失败,具体报错信息可参考后续的错误提示部分。
# yum install gcc-c++
# yum install pcre
# yum install pcre-devel
# yum install zlib
# yum install zlib-devel
# yum install openssl
# yum install openssl-devel
对下载的安装包进行解压处理。
# tar -zxvf nginx-1.11.5.tar.gz
Nginx 将被解压至 /usr/local/nginx-1.11.5 目录(注意:切勿将压缩包直接解压到 /usr/local/nginx 目录,也不要将解压后的文件夹重命名为 nginx,因为 Nginx 默认安装路径即为 /usr/local/nginx)。随后切换至 nginx-1.11.5/ 目录。
# cd /usr/local/nginx-1.11.5/
执行 # ./configure 命令。
# ./configure
该步骤用于检测当前系统环境,确保能够顺利安装 Nginx。执行后可能出现的几种提示如下:
checking for OS
+ Linux 3.10.0-123.el7.x86_64 x86_64
checking for C compiler ... not found
./configure: error: C compiler cc is not found
若出现上述错误,请执行 yum install gcc-c++ 来安装 GCC 编译器。
./configure: error: the HTTP rewrite module requires the PCRE library.
You can either disable the module by using --without-http_rewrite_module
option, or install the PCRE library into the system, or build the PCRE library
statically from the source with nginx by using --with-pcre= option.
出现以上提示表明系统缺少 PCRE 库。
./configure: error: the HTTP gzip module requires the zlib library.
You can either disable the module by using --without-http_gzip_module
option, or install the zlib library into the system, or build the zlib library
statically from the source with nginx by using --with-zlib= option.
若出现此类提示,说明缺少 zlib 库。
若未出现 ./configure: error 报错,则表明当前环境满足安装条件,可继续执行 make 和 make install 命令进行编译安装。
# make
# make install
若无错误输出,表示 Nginx 已成功安装,默认位置为 /usr/local/nginx。此时可删除之前的 /usr/local/nginx-1.11.5/ 目录。
若遇到 cp: 'conf/koi-win' and '/usr/local/nginx/conf/koi-win' are the same file 错误,通常是因为安装包被解压到了 /usr/local/nginx 目录。解决方法是将该目录重命名为其他名称,然后重新执行 make 和 make install。
配置 Nginx 开机自启动。
切换至 /lib/systemd/system/ 目录,创建 nginx.service 文件,使用 vim nginx.service 进行编辑。
# cd /lib/systemd/system/
# vim nginx.service
文件的具体配置内容如下:
[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx reload
ExecStop=/usr/local/nginx/sbin/nginx quit
PrivateTmp=true
[Install]
WantedBy=multi-user.target
保存并退出文件后,执行 systemctl enable nginx.service 以启用 Nginx 开机自启动。
# systemctl enable nginx.service
使用 systemctl start nginx.service 命令启动 Nginx 服务。
使用 systemctl stop nginx.service 命令停止 Nginx 服务。
使用 systemctl restart nginx.service 命令重启 Nginx 服务。
验证安装是否成功。
在浏览器中输入 http://服务器IP/,若能正常显示 Nginx 欢迎界面,则证明安装成功。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。