nginx的安装与配置(centos7.2)
一.安装步骤
1.安装必要库安装gcc环境 yum install gcc-c++
安装PCRE库 yum install -y pcre pcre-devel
安装zlib库 yum install -y zlib zlib-devel
安装OpenSSL yum install -y openssl openssl-devel
2.解压nginx.tar.gz包.
3.对nginx进行安装
①使用nginx包下的configure目录创建makeFile文件,指定安装路径等一些设置
nginx/configure \
--prefix=/usr/local/nginx \
--pid-path=/var/run/nginx/nginx.pid \
--lock-path=/var/lock/nginx.lock \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--with-http_gzip_static_module \
--http-client-body-temp-path=/var/temp/nginx/client \
--http-proxy-temp-path=/var/temp/nginx/proxy \
--http-fastcgi-temp-path=/var/temp/nginx/fastcgi \
--http-uwsgi-temp-path=/var/temp/nginx/uwsgi \
--http-scgi-temp-path=/var/temp/nginx/scgi
②创建临时目录,在上面的configure目录中定义的.
mkdir -p /var/temp/nginx/client
③安装nginx
nginx/make
nginx/make install
二.打开nginx
在configure命令中已经定义了prefix(安装目录)为/usr/local/nginxcd /usr/local/nginx/sbin
打开nginx ./nginx
重启nginx ./nginx -s reload
关闭nginx ./nginx -s quit
三.配置nginx
1.配置虚拟主机(根据nginx监听的端口或域名)①端口(通过配置不同listen属性的多个server)
server {
#nginx监听81端口,将请求转发给root,
listen 81;
server_name localhost;
location / {
#该root指向根目录下的html-81文件夹
root html81;
#返回root目录下的静态资源
index index.html index.htm;
}
}
server {
#nginx监听82端口
listen 82;
server_name localhost;
location / {
root html-82;
index index.html index.htm;
}
}
②域名(通过配置不同server_name属性的多个server)
#当请求域名为www.testNginx.com时响应
server {
#nginx监听83端口,将请求转发给root,
listen 83;
#将自己的hosts文件添加下面的内容
#nginx的IP:83 www.testNginx.com
server_name www.testNginx.com;
location / {
#该root指向根目录下的html-81文件夹
root html81;
#返回root目录下的静态资源
index index.html index.htm;
}
}
#当请求域名为www.test.com时响应
server {
#nginx监听83端口
listen 83;
server_name www.test.com;
location / {
root html82;
index index.html index.htm;
}
}
2.反向代理和负载均衡
1.配置server和upstream
#nginx转发的IP地址
upstream baidu {
server www.baidu.com;
}
#当请求域名为www.test1.com时,该server会将请求发送到proxy_pass
#最终拼装成http://www.baidu.com
server {
listen 84;
server_name www.test1.com;
location / {
proxy_pass http://baidu;
index index.html index.htm;
}
2.负载均衡,就是在upstream上添加多个server
#nginx转发的IP地址,weight=2表示所占权重
#例如有9个请求,转发到天猫可能有6次,淘宝有3次
upstream ali {
server www.taobao.com;
server www.tianmao.com weight=2;
}
#当请求域名为www.test1.com时,该server会将请求发送到proxy_pass
#最终拼装成http://www.taobao.com 或 http://www.tianmao.com
server {
listen 85;
server_name www.test1.com;
location / {
proxy_pass http://ali;
index index.html index.htm;
}