Nginx 下载地址 http://tengine.taobao.org
Nginx安装
1. 执行tar zxvf Nginx,tar 命令解压
2. 执行./configure 检查是否具备安装环境
1). gcc环境
安装Nginx需要先将官网下载的源码进行编译,编译依赖gcc环境,如果没有gcc环境,需要安装gcc:
yum install gcc-c++
2).PCRE环境
PCRE(Perl Compatible Regular Expressions)是一个Perl库,包括 perl 兼容的正则表达式库。Nginx的http模块使用pcre来解析正则表达式,所以需要在linux上安装pcre库
yum install -y pcre pcre-devel
3).zlib环境
zlib库提供了很多种压缩和解压缩的方式,nginx使用zlib对http包的内容进行gzip,所以需要在linux上安装zlib库。
yum install -y zlib zlib-devel
4)openssl环境
OpenSSL 是一个强大的安全套接字层密码库,囊括主要的密码算法、常用的密钥和证书封装管理功能及SSL协议,并提供丰富的应用程序供测试或其它目的使用。nginx不仅支持http协议,还支持https(即在ssl协议上传输http),所以需要在linux安装openssl库
yum install -y openssl openssl-devel
3. 执行 make 进行编译
4. 执行 sudo make install 命令安装nginx (默认安装目录 usr/local/nginx)
5. 修改配置文件 usr/local/nginx/cong/nginx.conf
实例配置:
#负载均衡
upstream backend {
server backend1.example.com weight=5;
server backend2.example.com:8080;
server unix:/tmp/backend3;
server backup1.example.com:8080 backup;
server 192.168.239.1:8080 max_fails=3 fail_timeout=30s;
server 192.168.239.129:8080 max_fails=3 fail_timeout=30s;
}
server {
#对外暴露一个80端口
listen 80;
server_name localhost;
#/代表无论输入任何地址,都会匹配到该地址(所有的路径,都会匹配以下的规则)
location / {
# 负载均衡到后台的wen服务器上(tomcat)
proxy_pass http://backend;
}
}
6.健康检查和检查登录密码
#检查需要被检查的ip(健康检查)
upstream backend {
server 192.168.239.129:8080 weight=1 max_fails=3 fail_timeout=30s;
server 192.168.239.1:8080 weight=1 max_fails=3 fail_timeout=30s;
check interval=3000 rise=2 fall=5 timeout=1000 default_down=false type=http;
#check_http_send "HEAD / HTTP/1.0\r\n\r\n";
check_http_expect_alive http_2xx http_3xx;
}
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
proxy_pass http://backend;
#当用户访问含有/admin/的路径 阻止访问(正则表达式匹配)
if ( $uri ~* ^/admin.*$ ) {
return 505;
}
}
location /status {
#登录注释
auth_basic "Password please";
#引用验证路径
auth_basic_user_file /usr/local/nginx/conf/htpasswd;
check_status;
access_log off;
#所有人访问允许 可根据ip限制 allow SOME.IP.ADD.RESS;
allow all;
#阻止所有人访问
#deny all;
}
yum -y install httpd 安装加密器插件
htpasswd -bc aa admin 123456 创建文件,给密码加密
7.session黏贴(两种方法)
# 默认配置:cookie=route mode=insert fallback=on
upstream foo {
server 192.168.0.1;
server 192.168.0.2;
session_sticky;
}
server {
location / {
proxy_pass http://foo;
}
}
#insert + indirect模式:
upstream test {
session_sticky cookie=uid domain=www.xxx.com fallback=on path=/ mode=insert option=indirect;
server 127.0.0.1:8080;
}
server {
location / {
#在insert + indirect模式或者prefix模式下需要配置session_sticky_hide_cookie
#这种模式不会将保持会话使用的cookie传给后端服务,让保持会话的cookie对后端透明
session_sticky_hide_cookie upstream=test;
proxy_pass http://test;
}
}
cookie设置用来记录会话的cookie名称
domain设置cookie作用的域名,默认不设置
path设置cookie作用的URL路径,默认不设置
maxage设置cookie的生存期,默认不设置,即为session
cookie,浏览器关闭即失效 mode设置cookie的模式:
8.检查,启动
执行 ./nginx -t 检查配置文件是否成功
usr/local/nginx/sbin/ 执行./nginx启动nginx
执行 ./nginx -s reload 重启