安装配置nginx的两种方式——yum安装和源码安装
访问nginx的官方网站:http://www.nginx.org/
Nginx版本类型
Mainline version: 主线版,即开发版
Stable version: 最新稳定版,生产环境上建议使用的版本
Legacy versions: 遗留的老版本的稳定版
一、通过Yum安装nginx
1、配置nginx的Yum源
安装说明:在新计算机上首次安装nginx之前,需要设置nginx软件包存储库。 之后,您可以从存储库安装和更新nginx。
[root@host ~]# cd /etc/yum.repos.d #进入yum源目录
[root@host yum.repos.d]# vim nginx.repo #添加下面内容到文件中
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1
[root@host yum.repos.d]# yum clean all && yum makeache #清理并加载缓存
[root@host yum.repos.d]# yum install nginx -y #下载安装nginx
[root@host yum.repos.d]# nginx -v #查看版本
nginx version: nginx/1.22.1
2、关闭防火墙和selinux
[root@host ~]# getenforce #查看selinux状态
Enforcing
[root@host ~]# setenforce 0 #关闭selinux
[root@host ~]# systemctl stop firewalld #关闭防火墙
[root@host ~]# systemctl disable firewalld #禁用防火墙
3、启动nginx
[root@host ~]# systemctl start nginx #启动nginx
[root@host ~]# systemctl enable nginx #设置开机自启
浏览器输入ip访问nginx服务器。
4、相关文件路径
yum安装配置文件位置:/etc/nginx/nginx.conf
网站主目录:/usr/share/nginx/html
日志文件目录:/var/log/nginx/
5、卸载nginx
[root@host ~]# yum remove nginx -y #卸载nginx
二、nginx源码安装
1、安装相关依赖包
安装gcc gcc-c++ pcre pcre-devel gd-devel(使nginx支持http rewrite模块)
安装openssl openssl-devel(使nginx支持ssl)
安装zlib zlib zlib-devel
[root@host ~]# yum -y install gcc gcc-c++ pcre pcre-devel gd-devel openssl openssl-devel zlib zlib-devel #下载依赖包
2、创建用户nginx
[root@host ~]# useradd nginx
3、安装nginx
[root@host ~]# wget http://nginx.org/download/nginx-1.18.0.tar.gz #从网络下载
[root@host ~]# tar -zxvf nginx-1.18.0.tar.gz #解压到当前目录
[root@host ~]# cd /nginx-1.18.0/ #进入nginx目录,方便在预编译时寻找文件
[root@host ~]# ./configure \ #预编译
--prefix=/usr/local/nginx \ #安装路径
--group=nginx \
--user=nginx \
--with-http_stub_status_module \
--with-http_v2_module \
--with-http_ssl_module \
--with-http_gzip_static_module \
--with-http_realip_module \
--with-http_flv_module \
--with-http_mp4_module \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module
[root@host ~]# make && make install #编译安装
4、添加环境变量
目的是为了在执行nginx的命令时不用输入命令的绝对路径,方便省事。
[root@host ~]# cat >>/etc/profile.d/nginx.sh<<EOF
export PATH=\${PATH}:/usr/local/nginx/sbin
EOF
[root@host ~]# source /etc/profile #使配置生效
5、启动nginx服务
[root@host ~]# nginx #直接启动
浏览器输入ip访问nginx服务器。
6、nginx相关命令
nginx -c /path/nginx.conf # 以特定目录下的配置文件启动nginx:
nginx -s reload # 修改配置后重新加载生效
nginx -s stop # 快速停止nginx
nginx -s quit # 正常停止nginx
nginx -t # 测试当前配置文件是否正确
nginx -t -c /path/to/nginx.conf # 测试特定的nginx配置文件是否正确
7、卸载nginx
删除安装路径下的nginx文件夹就行,想重新安装就进入nginx源码目录进行预编译。
注意:卸载之前先将nginx服务关掉。
[root@host ~]# rm -rf /usr/local/nginx/
注意:两种安装方式任选其一即可,不要同时使用,因为这样容易导致冲突,最终使服务出现异常。