RHEL/CentOS 下安装和配置 Nginx
引言
nginx (pronounced “engine x”) is an HTTP and reverse proxy server, as well as a mail proxy server. It is known for its high performance, stability, rich feature set, simple configuration, and low resource consumption.
众所周知,nginx 不但是一个 HTTP 服务和反向代理服务器,而且也是一个邮件代理服务器。
安装
不同的平台安装方法虽不同,但本质是一样的。
RHEL/CentOS
关闭 Apache 服务,并禁止开机启动:
CentOS 6 命令
1
2$ service httpd stop //停止;如需启动,将 stop 换成 start
$ chkconfig httpd off //禁止随 boot 启动;如需随系统启动,将 off 换成 onCentOS 7 命令
1
2$ systemctl stop httpd.service
$ systemctl disable httpd //如需随系统启动,将 disable 换成 enable
方法一
1、更新或者安装 EPEL 映射,里面有我们需要的 nginx 安装映射。1
$ yum install epel-release
2、通过 yum 命令工具进行安装1
$ yum -y install nginx
3、开启 nginx 服务1
2$ service nginx start // centos 6
$ systemctl start nginx // centos 7
4、将 nginx 服务配置随系统启动1
2$ chkconfig nginx on //centos 6 方法
$ systemctl enable nginx // centos 7 方法
方法二
本方法介绍安装 nginx 最新稳定版本,方法一只是安装 EPEL 中映射的版本。
1、首先设置 yum 映射,可通过 vi 或 vim 编辑器创建 /etc/yum.repos.d/nginx.repo
文件,将一下代码复制到此文件中。
1 | [nginx] |
2、根据你所使用的发布版本,替换上述代码中相应的参数,支持 6.x 和 7.x 版本。
- 将 “os” 替换成 “rhel” 或者 “centos”
- 将 “OSRELEASE” 替换成 “6” 或者 “7”
比如:在 CentOS 7下,如下配置:1
2
3
4
5[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1
3、配置好以上参数后,通过 yum install nginx
进行安装即可。
4、开启 nginx 服务,设置 nginx 随系统启动。1
2
3$ service nginx start //开始 nginx 服务
$ chkconfig nginx on //centos 6 系统设置方法
$ systemctl enable nginx //centos 7 设置方法
官方推荐方法
前期准备
1 | sudo yum install yum-utils |
设置 yum
repository, 创建一个 /etc/yum.repos.d/nginx.repo
文件,并包含下面内容:
1 | [nginx-stable] |
默认情况下会使用 nginx
稳定包,如果想使用公测版,可以运行下面命令:
1 | sudo yum-config-manager --enable nginx-mainline |
通过 yum
安装 nginx
1 | sudo yum install nginx |
更多详细内容请点击官方文档
配置
RHEL/CentOS
安装成功后,系统一般会告诉你服务配置文件 /etc/nginx/nginx.conf
和服务器的位置 /usr/share/nginx/html
。
编辑配置文件时,请注意倒数第 2 行 include /etc/nginx/conf.d/*.conf;
,意思是所有的配置文件可以独立出来,nginx.conf 都会读取 conf.d 目录下的所有的 .conf 文件。在 conf.d 目录下,系统默认提供 default.conf 配置文件,我们简单的进行编辑即可。
常见命令
1、检测配置是否有误,并按照错误提示进行修改。1
$ nginx -t
2、重新载入 nginx 配置服务文件1
$ service nginx reload
3、启动、重启和停止1
2
3$ service nginx [start、restart 和 stop] //[启动、重启和停止]
或
$ systemctl status [start|restart|stop] nginx
负载均衡
简单配置1
2
3
4
5
6
7
8
9
10
11
12
13upstream myproject {
server blogtao.github.io weight=2;
server blogtao.github.io weight=5;
}
server {
listen 80;
server_name vip.devhitao.com;
location / {
proxy_pass http://myproject;
}
}
参考链接
- nginx documentation
- nginx: Linux packages
- How to install and configure NGINX on CentOS 6
- How to install and configure NGINX on CentOS 7
文档信息
- 版权声明:自由转载-保持署名-非商用-非衍生 ( CC BY-NC-ND 4.0 )