(1)Nginx的安装
相关文档:Nginx维护包的官方网站:http://nginx.org
Nginx官方文档:http://nginx.org/en/docs/
淘宝团队翻译文档:http://tengine.taobao.org/documentation_cn.html
Nginx开发从入门到精通: http://tengine.taobao.org/book/index.html
1、nginx 源码下载:http://nginx.org/en/download.html
2、依赖
PCRE库(是一个用C语言编写的正则表达式函数库,由菲利普.海泽(Philip Hazel)编写)
zlib库(是提供数据压缩用的函数库,zlib能使用一个gzip数据头,zlib数据头或者不使用数据头压缩数据。)
OpenSSL开发库(是一个安全套接字层密码库,囊括主要的密码算法、常用的密钥和证书封装管理功能及SSL协议,并提供丰富的应用程序供测试或其它目的使用。)
a.tar -zxvf nginx-1.10.1.tar.gz
b.cd nginx-1.10.1/
c../configure –with-pcre=pcre的源码目录 –with-zlib=zlib的源码目录 –with-openssl的源码目录
./configure –help(查看帮助)
–with-pcre=pcre的源码目录
–with-zlib=zlib的源码目录
–with-openssl的源码目录
d.make
e.sudo make install
默认nginx放置在/usr/local/nginx
添加软连接到/usr/local/bin
sudo ln -s /usr/local/nginx/sbin/nginx /usr/local/bin/
启动nginx
sudo nginx
(2)Nginx的配置 (sudo nginx -t 可以查看配置路径)
user nobody; 指用哪个用户启动worker进程
worker_processes 1; worker进程数量,跟CPU核心数相等
error_log logs/error.log;
http
include mime.types; 将某个文件在这里展开
default_type application/octet-stream;
access_log 地址;
server 模块
listen 80;监听80端口 用于http,https使用443
listen ip:port; 不填ip,默认0.0.0.0
server_name 域名; 只能填域名
charset koi8-r;
默认字符集 ,俄罗斯文
修改为utf-8
location 模块
配置资源定位
location / { http://ip:port/
root html;
指定资源从哪个目录搜索,可以是绝对路径也可以是相对于prefix
的路径
index index.html index.htm ...;
如果请求资源定位是一个目录,那么默认返回哪个文件,用来定义主页
首先搜索index.html ,搜索不到再搜索index.htm
}
域名和ip
域名 www.baidu.com
一个域名 : 同一个地方同一个时刻,只能对应一个IP
一个IP 可以绑定多个域名
如何通过域名来解析出IP?
1 自行解析 通过hosts
linux/unix/mac /etc/hosts
windows : C:/windows/system32/driver/etc/hosts
2 DNS (Domain Name System) 前提:要配置DNS
当前主机会发送一个UDP报文到DNS服务器
服务器回一个报文告诉IP地址
虚拟主机
同一个端口80部署不同的站点
网络层/控制层 IP/TCP 不能做区分
应用层 http 做区分
在http请求头的
Host字段 : www.baidu.com 作区分
需求:
www.A.cn
www.B.cn
使用以上两个域名来访问nginx服务器,里应该看到两个不同的页面
使用多个server模块来配置nginx
<h1>welcome to A</h1>
server {
listen 80;
server_name www.A.cn;
charset utf-8;
location / {
root /home/A/www/A/;
index index.html index.htm;
}
}
server {
listen 80;
server_name www.B.cn;
charset utf-8;
location / {
root /home/B/www/B/;
index index.html index.htm;
}
}
反向代理配置
反向代理配置
使用proxy_pass
location / {
proxy_pass http://ip:port;
}
location / {
proxy_pass http://192.168.111.111:10080;
#proxy_set_header Host www.A.cn;
//端口一致,反向代理通过set_header 来区分访问那个服务器
}
负载均衡
实现负载均衡的前提是实现反向代理
只有实现反向代理才有权限做决策
要在http模块下(不是server模块)
添加服务器群组 ,给其他代理做引用
upstream 群组名字 {
server ip1:port1;
server ip2:port2;
server unix:/tmp/aaa.sock;
}
server模块下
location / {
proxy_pass http://群组名字;
}
默认是轮询策略
权重与备用
多台服务器,配置不一,性能好的服务器想多分摊一点请求,设置权重
upstream test.cn {
server 192.168.177.163:10080 weight=90;
server 192.168.177.163:10081 weight=10;
}
请求分配计算,将所有权重相加,求百分比
备用
有一些服务器只做备用,当其他服务器挂了,就启用
upstream test.cn {
server 192.168.177.163:10080;
server 192.168.177.163:10081 backup;
}
好乱 。。。 赶时间。。。