CentOS安装Nginx

最后更新于:2023-04-14 11:13:05

、安装前的准备:


1. 更新系统软件:

yum update


2. 查看是否已安装wget: rpm -qa wget 否则安装:

yum install –y wget


3. 查看是否已安装编译器: rpm -qa gcc 否则安装:

yum install -y gcc gcc-c++
yum install wget vim lrzsz gcc gcc-c++ pcre pcre-devel openssl openssl-devel zlib zlib-devel automake autoconf libtool make

二、安装Nginx


1. 安装nginx依赖包


nginx的Rewrite模块和HTTP核心模块会使用到PCRE正则表达式语法:

yum -y install pcre pcre-devel


nginx的各种模块中需要使用gzip压缩:

yum -y install zlib zlib-devel

安全套接字层密码库:

yum -y install openssl openssl-devel

2. 下载nginx包并解压(到/usr/local/src目录中)

cd /usr/local/src
tar -zxvf nginx-1.20.1.tar.gz

3. 编译安装(到/usr/local/nginx目录中)

cd nginx-1.20.1

./configure
make
make install

【make未找到】

yum -y install automake autoconf libtool make

4. 创建nginx用户:

groupadd nginx
useradd -g nginx -s /sbin/nologin -M nginx
#-g:指定所属的group
#-s:指定shell,因为它不需要登录,所以用/sbin/nologin
#-M:不创建home目录,因为它不需要登录

编辑配置文件:

cd /usr/local/nginx/conf
vim nginx.conf


设置user参数如下:

user nginx nginx;

5. 日志记录配置【在配置文件里增加如下内容,放在http { 内 }

log_format main '$remote_addr - $remote_user [$time_iso8601] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" $upstream_response_time $request_time';
access_log logs/access.log main;
ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/ #看个人需要

6. 启动一次nginx,然后再平滑重起

nginx
nginx -s reload

【找不到nginx】

echo "export PATH=$PATH:/usr/local/nginx/sbin" >>/etc/profile
source /etc/profile

错误提示:

nginx: [error] open() "/usr/local/nginx/logs/nginx.pid" failed (2: No such file or directory)


【启动失败,可重启服务器】

7. 配置开机启动nginx服务

vim /usr/lib/systemd/system/nginx.service

【复制如下内容至文件】

[Unit]
Description=nginx-The High-performance HTTP Server
After=network.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true
[Install]
WantedBy=multi-user.target

设置nginx开机自启动:

systemctl enable nginx.service


开启nginx服务:

systemctl start nginx.service

常用命令:

/usr/local/nginx/sbin/nginx -v 查看Nginx版本(小v)
/usr/local/nginx/sbin/nginx -V 查看nginx的配置编译参数(大V)
/usr/local/nginx/sbin/nginx 启动
/usr/local/nginx/sbin/nginx -s stop 停止
/usr/local/nginx/sbin/nginx -s reload 重启
/usr/local/nginx/sbin/nginx -t 检测语法错误
/usr/local/nginx/sbin/nginx -V 2>&1 | tr -- - '\n' | grep module # 查看安装了那些模块

=========================================================================


Error: The GeoIP module requires the GeoIP library –
解决办法:

yum install geoip-devel

./configure: error: the Google perftools module requires the Google perftools library.
You can either do not enable the module or install the library.
解决办法:

yum install gperftools

nginx: [error] open() "/usr/local/nginx/logs/nginx.pid" failed (2: No such file or directory)
解决办法:启动失败,可重启服务器