CentOS 7 安装Nginx 并配置自动启动

1、官网下载安装包

http://nginx.org/en/download.html
选择适合Linux的版本,这里选择最新的版本,下载到本地后上传到服务器或者centos下直接wget命令下载。

image.png

切换到/usr/local目录,下载软件包

cd /usr/local
wget http://nginx.org/download/nginx-1.11.5.tar.gz

2、安装nginx

先执行以下命令,安装nginx依赖库,如果缺少依赖库,可能会安装失败,具体可以参考文章后面的错误提示信息。

yum install -y gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel

解压安装包

# nginx被解压到了/usr/local/nginx-1.11.5 目录下(不要把压缩包解压到/usr/local/nginx目录下,或者将解压后的目录重命名为nginx,因为nginx会默认安装到/usr/local/nginx目录下),切换到nginx-1.11.5/目录

tar -zxvf nginx-1.11.5.tar.gz

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=<path> 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=<path> option.

如果出现以上提示,表示缺少zlib库
如果没有出现./configure: error提示,表示当前环境可以安装nginx,执行make和make install编译nginx

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.

3、配置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使nginx开机启动

# 启用服务
systemctl enable nginx
# 启动nginx (原本使用过默认方式启动nginx的可能会导致服务启动失败,将原本的nginx进程kill掉,然后使用当前方式启动即可)
systemctl start nginx
# 结束nginx
systemctl stop nginx
#  重启nginx
systemctl restart nginx
# 查看启动状态
systemctl status nginx

4、验证是否安装成功

输入http://服务器IP/ 如果能看到nginx的界面,就表示安装成功了

作者:jockming
写博文不易,希望大家多多支持。评论一定一一回复
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
原文地址:https://www.cnblogs.com/jockming/p/14849649.html