【web负载均衡集群之nginx-03】

一、nginx-web服务

Nginx(发音同engine x)是一款由俄罗斯程序员Igor Sysoev所开发轻量级的网页服务器、反向代理服务器以及电子邮件(IMAP/POP3)代理服务器。
官方介绍:http://nginx.org/en/

1.Nginx重要特性

具备如下基本特性:
□ 可针对静态资源高速高并发访问及缓存。
□ 可使用反向代理加速,并且可进行数据缓存。
□ 具有简单负载均衡、节点健康检查和容错功能。
□ 支持远程 FastCGI 服务的缓存加速。
□ 支持 FastCGI 、Uwsgi 、SCGI 、 Memcached Servers 的加速和缓存。
□ 支持 SSL 、TLS 、SNI。
□ 具有模块化的架构:过滤器包括 gzip 压缩 、ranges 支持、chunked 响应 、 XSLT、SSI 及图像缩放
等功能。在 SSI 过滤器中,一个包含多个 SSI 的页面,如果经由FastCGI 或反向代理处理,可被并行处
理。
所具备的其他 WWW 服务特性如下:
□ 支持基于名字、端口及 IP 的多虚拟主机站点。
□ 支持 Keep-alive 和 pipelined 连接。
□ 可进行简单 、方便、灵活的配置和管理。
□ 支持修改 Nginx 配置,并且在代码上线时,可平滑重启,不中断业务访问。
□ 可自定义访问日志格式,临时缓冲写日志操作,快速日志轮询及通过 rsyslog 处理日志。
□ 可利用信号控制 Nginx 进程。
□ 支持 3xx-5xx HTTP 状态码重定向。
□ 支持 rewrite 模块,支持 URI 重写及正则表达式E配。
□ 支持基于客户端 IP 地址和 HTTP 基本认证的访问控制。
□ 支持 PUT 、 DELETE 、 MKCOL 、 COPY 及 MOVE 等较特殊的 HTTP 请求方法。
□ 支持 FLV 流和 MP4 流技术产品应用。
□ 支持 HTTP 响应速率限制。
□ 支持同一 IP 地址的并发连接或请求数限制。
□ 支持邮件服务代理。

2.Nginx 软件的主要企业功能应用

( 1 ) 作为 Web 服务软件
( 2 ) 反向代理或负载均衡服务
( 3 ) 前端业务数据缓存服务

二、nginx安装

1.rpm安装

RPM包获取: http://nginx.org/packages/

#获取rpm包然后进行安装:
yum install -y nginx 
#启动服务
systemctl start nginx
#Nginx主配置文件目录:/etc/nginx/nginx.conf
#Nginx访问页面文件目录:/usr/share/nginx/www/
#查看版本信息:nginx -v
[root@manager ~]# nginx -v
nginx version: nginx/1.10.0
#对配置文件进行语法检测:nginx -t
[root@manager ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
#查看nginx编译参数:nginx -V
[root@manager conf.d]# nginx -V
nginx version: nginx/1.10.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-4) (GCC) 
built with OpenSSL 1.0.1e-fips 11 Feb 2013
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp 

2.源码安装

源码包获取:http://nginx.org/download/

#1.安装所需依赖包
yum install -y pcre-devel (为了使 Nginx 支持具备 URI 重写功能的 rewrite 模块)
yum install -y openssl-devel ( HTTPS 服务的时候要用到此模块)
yum install gcc gcc-c++ make -y (提供编译工具)
2.创建nginx用户,nginx组
groupadd -r -g 995 nginx
useradd -r -u 995 -g 995  -s /sbin/nologin -M nginx
3.获取源码包,然后编译安装
[root@node1 ~]# wget http://nginx.org/download/nginx-1.10.0.tar.gz
#解压
[root@node1 ~]# tar -xf nginx-1.10.0.tar.gz -C /usr/local/src/
#切到解压目录,进行编译安装
[root@node1 ~]# cd /usr/local/src/nginx-1.10.0
[root@node1 ~]# ./configure  --user=nginx group=nginx  --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
...
...
nginx path prefix: "/usr/local/nginx"
nginx binary file: "/usr/local/nginx/sbin/nginx"
nginx modules path: "/usr/local/nginx/modules"
nginx configuration prefix: "/usr/local/nginx/conf"
nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
nginx pid file: "/usr/local/nginx/logs/nginx.pid"
nginx error log file: "/usr/local/nginx/logs/error.log"
nginx http access log file: "/usr/local/nginx/logs/access.log"
nginx http client request body temporary files: "client_body_temp"
nginx http proxy temporary files: "proxy_temp"
nginx http fastcgi temporary files: "fastcgi_temp"
nginx http uwsgi temporary files: "uwsgi_temp"
nginx http scgi temporary files: "scgi_temp"
# 编译并安装
[root@node1 ~]# make && make install
4.提供系统服务启动脚本
[root@node1 ~]# vim /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target
 
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
 
[Install]
WantedBy=multi-user.target
5.启动服务
[root@node1 ~]# systemctl start nginx
[root@node1 ~]# ps -ef | grep nginx
root       8403      1  0 09:01 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/ngin -c /usr/local/nginx/conf/nginx.conf
nobody     8404   8403  0 09:01 ?        00:00:00 nginx: worker process
root      16167   1759  0 10:38 pts/0    00:00:00 grep --color=auto nginx

注1:统计nginx访问日志前5个IP

#rpm包访问日志
[root@node1 ~]# tail/var/log/nginx/access.log | awk '{IP[$1]++} END{for (k in IP) {print IP[k],k} }'| sort -nr| head -5
#源码访问日志
[root@node1 ~]# tail /usr/local/nginx/logs/access.log | awk '{IP[$1]++} END{for (k in IP) {print IP[k],k} }'| sort -nr| head -5

注2:nginx增加第三方模块
https://www.cnblogs.com/anttech/p/10687163.html
注3:nginx模块
1.nginx核心模块
Nginx 核心功能模块负责 Nginx 的全局应用,主要对应主配置文件的 Main 区块和Events 区块区域
2.http功能模块:绝大部分默认情况都会自动安装到 Nginx 软件中
在这里插入图片描述
注:Nginx目录结构说明

[root@node1 ~]# tree /usr/local/nginx/
/usr/local/nginx/
├── client_body_temp
├── conf  #配置文件目录
│   ├── fastcgi.conf  #fastcgi相关参数的配置文件
│   ├── fastcgi.conf.default #fastcgi.conf的原始备份
│   ├── fastcgi_params #fastcgi的参数文件
│   ├── fastcgi_params.default 
│   ├── koi-utf
│   ├── koi-win
│   ├── mime.types #媒体类型
│   ├── mime.types.default 
│   ├── nginx.conf #Nginx主配置文件
│   ├── nginx.conf.default 
│   ├── scgi_params #Scgi相关参数文件
│   ├── scgi_params.default
│   ├── uwsgi_params #uwsgi相关参数文件
│   ├── uwsgi_params.default
│   └── win-utf
├── fastcgi_temp #fastcgi临时数据目录
├── html  #编译安装时Nginx的默认站点目录,类似apache的htdocs目录
│   ├── 50x.html #出现502错误时会调用该页面
│   └── index.html
├── logs #日志目录
│   ├── access.log #访问日志
│   ├── error.log #错误日志
│   └── nginx.pid #pid文件
├── proxy_temp
├── sbin #nginx命令目录
│   ├── nginx
│   └── nginx.old
├── scgi_temp #临时目录
└── uwsgi_temp #临时目录

9 directories, 22 files

注:配置文件说明

[root@manager conf.d]# cat /usr/local/nginx/conf/nginx.conf
worker_processes 1;        ← worker 进程数量
events {              ←事件区块
  worker_connections 1024;    ←每个worker进程可以处理的连接数
}                  ←事件区块结束
http {                    ← HTTP 区块
  include    mime.types;        ←支持的媒体文件
  default_type application/octet-stream; ←默认的媒体类型
  sendfile    on;           ←高效传输模式
  keepalive_timeout 65;          ←超时时间
  server {                 ← server 区块
    listen    80;           ←端口
    server_name localhost;       ←域名
    location / {             ←第一个location区块
      root  html;           ←站点目录
      index  index.html index.htm;   ←首页文件
   }                   ←第一个location区块结束
    error_page  500 502 503 504 /50x.html;  ← 错误信息配置
    location = /50x.html {          文件位置
      root  html;             在哪找:路径
   }                  
 }                     ← server 区块结束
}                       ← HTTP 区块结束

三、nginx-web应用

1.虚拟主机配置

[root@manager conf.d]# mv default.conf{,.bak}
#创建站点目录
[root@manager html]# for name in bbs blog news
> do
> mkdir $name
> done
#创建主页文件
[root@manager html]# for name in bbs blog news; do echo "$name test page" > $name/index.html; done
[root@manager html]# tree ./
./
├── 50x.html
├── bbs
│   └── index.html
├── blog
│   └── index.html
├── index.html
├── index.html.bak
└── news
    └── index.html

1.1基于IP的虚拟主机配置

1.添加IP地址
[root@manager html]# nmcli connection modify ens33 +ipv4.addresses 192.168.131.106/24 
[root@manager html]# nmcli connection modify ens33 +ipv4.addresses 192.168.131.105/24 
[root@manager html]# nmcli connection up ens33
连接已成功激活(D-Bus 活动路径:/org/freedesktop/NetworkManager/ActiveConnection/2[root@manager html]# nmcli connection reload
2.配置虚拟主机文件
#进入子配置目录
[root@manager html]# cd /etc/nginx/conf.d/
[root@manager conf.d]# vim vhost.conf 
server {
    listen       192.168.131.107:80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html/bbs/;
        index  index.html index.htm;
    }
}

server {
    listen       192.168.131.106:80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html/blog/;
        index  index.html index.htm;
    }
}
server {
    listen       192.168.131.105:80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html/news/;
        index  index.html index.htm;
    }
}
3.重启服务
[root@manager conf.d]# systemctl restart nginx
4.测试
[root@manager conf.d]# curl 192.168.131.107
bbs test page
[root@manager conf.d]# curl 192.168.131.106
blog test page
[root@manager conf.d]# curl 192.168.131.105
news test page

1.2基于端口的虚拟主机配置

[root@manager conf.d]# vim vhost.conf 
server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html/bbs/;
        index  index.html index.htm;
    }
}

server {
    listen       81;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html/blog/;
        index  index.html index.htm;
    }
}
server {
    listen       82;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html/news/;
        index  index.html index.htm;
    }
}
测试:
[root@manager conf.d]# systemctl restart nginx
[root@manager conf.d]# curl 192.168.131.107:80
bbs test page
[root@manager conf.d]# curl 192.168.131.107:81
blog test page
[root@manager conf.d]# curl 192.168.131.107:82
news test page

1.3基于域名的虚拟主机配置

[root@manager conf.d]# vim vhost.conf 
server {
    listen       80;
    server_name  bbs.nginx.com;

    location / {
        root   /usr/share/nginx/html/bbs/;
        index  index.html index.htm;
    }
}

server {
    listen       80;
    server_name  blog.nginx.com;

    location / {
        root   /usr/share/nginx/html/blog/;
        index  index.html index.htm;
    }
}
server {
    listen       80;
    server_name  news.nginx.com;

    location / {
        root   /usr/share/nginx/html/news/;
        index  index.html index.htm;
    }
}
#配置IP地址与域名对应文件
[root@manager conf.d]# vim /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.131.107 bbs.nginx.com blog.nginx.com news.nginx.com
测试:
[root@manager conf.d]# curl bbs.nginx.com
bbs test page
[root@manager conf.d]# curl blog.nginx.com
blog test page
[root@manager conf.d]# curl news.nginx.com
news test page

2.日志配置

nginx的两种日志种类:
错误日志:记录nginx运行错误情况信息
访问日志:记录用户访问日志信息

2.1配置错误日志

系统默认配置
#rpm
error_log  /var/log/nginx/error.log warn;
#源码
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

2.2配置访问日志

access_log  /var/log/nginx/access.log  main; 
#访问日志文件内格式设置
log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
[root@manager news]# tail /var/log/nginx/access.log
192.168.131.107 - - [05/Aug/2020:12:27:21 +0800] "GET / HTTP/1.1" 200 1308 "-" "curl/7.29.0" "-"
192.168.131.107 - - [05/Aug/2020:12:29:42 +0800] "GET / HTTP/1.1" 200 1308 "-" "curl/7.29.0" "-"
192.168.131.107 - - [05/Aug/2020:12:32:37 +0800] "GET / HTTP/1.1" 200 14 "-" "curl/7.29.0" "-"
192.168.131.107 - - [05/Aug/2020:12:32:49 +0800] "GET / HTTP/1.1" 200 14 "-" "curl/7.29.  
格式说明:
$remote_addr:客户端地址 $remote_user:远程访问用户 [$time_local]:访问时间 $request:请求行信息 $status:状态码 $body_bytes_sent:响应报文主体内容大小 $http_user_agent:客户端浏览网页信息工具 $http_x_forwarded_for:反向代理转发

2.2配置访问日志轮询(日志切割)

第一种方法:系统的日志轮转(系统级计划任务)

[root@node1 ~]# vim /etc/logrotate.d/nginx
/usr/local/nginx/logs/*.log {
		dateext             #会用日期来作为日志文件的后缀
        daily
        missingok
        rotate 30
        compress
        delaycompress
        notifempty
        create 640 nginx adm
        sharedscripts
        postrotate
                [ -f /usr/local/nginx/logs/nginx.pid ] && kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
        endscript
}
#强制执行日志轮转文件
[root@node1 logs]# logrotate -f /etc/logrotate.d/nginx
[root@node1 logs]# ll
总用量 12
-rw-r----- 1 nobody adm    0 8月   5 12:56 access.log
-rw-r--r-- 1 root   root 425 8月   5 09:01 access.log-20200805
-rw-r----- 1 nobody adm    0 8月   5 12:56 error.log
-rw-r--r-- 1 root   root 264 8月   5 09:01 error.log-20200805
-rw-r--r-- 1 root   root   5 8月   5 09:01 nginx.pid

dateext #添加此参数会用日期来作为日志文件的后缀,不添加日志文件就需要改名,自动改名为xxxx.1 xxxx.2等
第二种方法:编写脚本的日志轮转(用户级计划任务)

[root@node1 scripts]# cat cut_nginx_log.sh 
#!/bin/bash
date_format=$(date +%F)
log_dir=/usr/local/nginx/logs
log_name=access

[ -d $log_dir ] && cd $log_dir || exit 1
[ -f $log_dir/$log_name.log ] || exit 1

mv $log_dir/$log_name.log $log_dir/${log_name}_$date_format.log
/usr/local/nginx/sbin/nginx -s reload
[root@node1 scripts]# sh cut_nginx_log.sh
查看日志目录:
[root@node1 scripts]# ll /usr/local/nginx/logs/
总用量 12
-rw-r--r-- 1 root root 425 85 09:01 access_2020-08-05.log
-rw-r--r-- 1 root root 264 85 09:01 error.log
-rw-r--r-- 1 root root   5 85 09:01 nginx.pid

3.常用功能配置

3.1当首页文件不存在时,可以部署文件共享

[root@manager news]# cd /usr/share/nginx/html/news/
[root@manager news]# mv index.html{,.bak}
[root@manager news]# touch file{1..9}.txt
[root@manager news]# ls
-rw-r--r-- 1 root root  0 85 12:25 file1.txt
-rw-r--r-- 1 root root  0 85 12:25 file2.txt
-rw-r--r-- 1 root root  0 85 12:25 file3.txt
-rw-r--r-- 1 root root  0 85 12:25 file4.txt
-rw-r--r-- 1 root root  0 85 12:25 file5.txt
-rw-r--r-- 1 root root  0 85 12:25 file6.txt
-rw-r--r-- 1 root root  0 85 12:25 file7.txt
-rw-r--r-- 1 root root  0 85 12:25 file8.txt
-rw-r--r-- 1 root root  0 85 12:25 file9.txt
index.html.bak

添加autoindex on;

[root@manager news]# vim /etc/nginx/conf.d/vhost.conf 
server {
    listen       80;
    server_name  news.nginx.com;

    location / {
        root   /usr/share/nginx/html/news/;
        index  index.html index.htm;
		autoindex on; 
    }
}
[root@manager html]# systemctl restart nginx
#在windows下的C:\Windows\System32\drivers\etc/hosts添加:
192.168.131.107 bbs.nginx.com blog.nginx.com news.nginx.com 

测试:
在这里插入图片描述

3.2添加状态模块nginx_status

添加:

location /nginx_status {
  stub_status on;
  access_log off;
}
[root@manager html]# vim /etc/nginx/conf.d/vhost.conf 
server {
    listen       80;
    server_name  news.nginx.com;

    location / {
        root   /usr/share/nginx/html/news/;
        index  index.html index.htm;
    }
    location /status {
		stub_status on;
		access_log off;
    }
}
[root@manager html]# systemctl restart nginx

测试:在这里插入图片描述
注:每次页面被访问一次,accepts,handle,request都加1。
Active connections 当前的活动客户端连接数量
accepts 接受客户端连接的总数
handled 处理的连接总数
requests 客户端请求的总数
Reading nginx正在读请求头的当前连接数。
Writing nginx正在将响应写回客户端的当前连接数。
Waiting 当前空闲客户端连接数等待一个请求。

3.3nginx的location指令

语法:
location [=|~|~*|^~] uri {

}

在这里插入图片描述

[root@manager html]# vim /etc/nginx/conf.d/vhost.conf
server {
    listen       80;
    server_name  news.nginx.com;

	location / {
		return 401;	
	}
	location =/ {
		return 402;	
	}
	location /documents/ {
		return 403;	
	}
	location ^~/images/ {
		return 404;	
	}
	location ~*\.(gif|jpg|jpeg)$ {
		return 500;	
	}
}
[root@manager html]#  curl -I -w "%{http_code}\n" -o /dev/null -s news.nginx.com
402
[root@manager html]#  curl -I -w "%{http_code}\n" -o /dev/null -s news.nginx.com/documents
401
[root@manager html]# curl -I -w "%{http_code}\n" -o /dev/null -s news.nginx.com/documents/
403
[root@manager html]# curl -I -w "%{http_code}\n" -o /dev/null -s news.nginx.com/images/abc.jpg/
404
[root@manager html]# curl -I -w "%{http_code}\n" -o /dev/null -s news.nginx.com/documents/abc.jpg
500

3.4nginx的rewrite模块

Nginx rewrite 的主要功能也是实现 URL 地址重写。
1)rewrite 指令语法
指令语法: rewrite regex replacement [flag]; (rewrite 正则表达式 重定向的位置 flagBiaoji )
默认值:none
应用位置: server、 location、 if

在这里插入图片描述
2)Nginx rewrite 的企业应用场景
可以调整用户浏览的 URL,看起来更规范,合乎开发及产品人员的需求。
为了让搜索引擎搜录网站内容及用户体验更好,企业会将动态 URL地址伪装成静态地址提供服务。
网址换新域名后,让旧的访问跳转到新的域名上。例如,访问京东的 360buy.com会跳转到jd.com
根据特殊变量、目录、客户端的信息进行 URL调整等
实例1:如果访问不存在的任意网页都重定向到错误页面

[root@manager html]# vim /etc/nginx/conf.d/vhost.conf
server {
    listen       80;
    server_name  news.nginx.com;
	location / {
		root /usr/share/nginx/html/news/;
		index index.html index.htm;
		if (!-f $request_filename) {
			rewrite /.* err.html permanent;
		}
	}
}
#如果news.nginx.com/后面的url不存在则永久重定向到/usr/share/nginx/html/news/err.html
[root@manager html]# systemctl restart nginx
#写一个err.html重定向的页面
[root@manager html]# vim news/err.html 
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>error page</title>
</head>
<body>
<h1>这是一个错误页面!</h1>
</body>
</html>

测试:
在这里插入图片描述
在这里插入图片描述
实例 2:为某个目录定义别名,用户访问的路径其实并不存在,而是将其转发到另外一个页面

[root@manager html]# cat /etc/nginx/conf.d/vhost.conf
server {
    listen       80;
    server_name  news.nginx.com;
	location / {
		root /usr/share/nginx/html/news/;
		index index.html index.htm;
		rewrite ^/test/(.*) /report/$1 last;
	}

}
[root@manager html]# systemctl restart nginx
[root@manager html]# mkdir news/report
[root@manager html]# vim news/report/test.html
welcome to test page!
[root@manager html]# ls news/
err.html  index.html  report

测试:在这里插入图片描述
实例 3:实现域名跳转

[root@manager html]# vim /etc/nginx/conf.d/vhost.conf
server {
    listen       80;
    server_name  news.nginx.com;
	location / {
		root /usr/share/nginx/html/news/;
		index index.html index.htm;
		rewrite ^/(.*) http://www.baidu.com last;
	}
}
[root@manager html]# systemctl restart nginx

测试:
在这里插入图片描述
在这里插入图片描述
注:域名跳转建议跳转到其他的web服务器上

4.访问认证

4.1基于地址访问控制

语法: deny address | CIDR | unix: | all;
语法: allow address | CIDR | unix: | all;

提示:从上到下的顺序,类似iptables。匹配到了便跳出。

[root@manager html]# cat /etc/nginx/conf.d/vhost.conf
server {
    listen       80;
    server_name  news.nginx.com;
	location / {
		root /usr/share/nginx/html/news/;
		index index.html index.htm;
		deny 192.168.131.108;
		allow 192.168.131.0/24;
	}
}

测试:
192.168.131.108:

[root@node1 ~]# curl  news.nginx.com
<html>
<head><title>403 Forbidden</title></head>
<body bgcolor="white">
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.10.0</center>
</body>
</html>

192.168.131.107:
在这里插入图片描述

4.2基于用户访问控制

[root@manager html]# vim /etc/nginx/conf.d/vhost.conf
server {
    listen       80;
    server_name  news.nginx.com;
	location / {
		root /usr/share/nginx/html/news/;
		index index.html index.htm;
		auth_basic "Restricted";
		auth_basic_user_file /test/webpasswd;
	}
}
[root@manager html]# systemctl restart nginx
[root@manager html]# mkdir -p /test/webpasswd
[root@manager html]# htpasswd -c /test/webpasswd tom
New password: 
Re-type new password: 
Adding password for user tom

测试:
在这里插入图片描述
在这里插入图片描述

4.3基于对扩展名文件访问控制

[root@manager html]# cat /etc/nginx/conf.d/vhost.conf
server {
    listen       80;
    server_name  news.nginx.com;
	location / {
		root /usr/share/nginx/html/news/;
		index index.html index.htm;
	}
	location ~\.txt$ {
		deny all;
	}
}
[root@manager html]# systemctl restart nginx

在这里插入图片描述

5.浏览器本地缓存设置

语法:expires [time|epoch|max|off]
默认值:expires off
作用域:http,server,location
用途:使用本指令可以控制HTTP应答中的“Expires”和“Cache-Control”的Header头信息(起到控制页面缓存作用)。

示例:对常见格式的图片、flash文件在浏览器本地缓存30天,对js、css文件在浏览器在本地缓存1小时;

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*\.(js|css)?*
{
expires 1h;
}

四、LNMP环境应用

在这里插入图片描述

1.FastCGI 介绍

CGI 的全称为 “通用网关接口”( Common Gateway Interface ), 为 HTTP 服务器与其他机器上的程序服务通信交流的一种工具, CGI 程序须运行在网络服务器上。
FastCGI 是一个可伸缩地、 高速地在 HTTP 服务器和动态脚本语言间通信的接口( 在 Linux 下,FastCGI 接口即为 socket, 这个 socket 可以是文件 socket, 也 可 以 是 IP socket ), 主要优点是把动态语言和 HTTP 服务器分离开来。 多数流行的 HTTP 服务器都支持 FastCGI, 包括 Apache 、 Nginx 和Lighttpd 等。 FastCGI 也被许多脚本语言所支持, 例如当前比较流行的脚本语言 PHP

2.搭建LNMP环境以及部署论坛

https://blog.csdn.net/qq_40003309/article/details/107837612

五、nginx web服务优化

六、nginx反向代理及负载均衡

1.代理服务器

1.1什么是代理服务器

代理服务器,客户机在发送请求时,不会直接发送给目的主机,而是先发送给代理服务器,代理服务接受客户机请求之后,再向主机发出,并**接收目的主机返回的数据,**存放在代理服务器的硬盘中,再发送给客户机。

1.2.为什么要使用代理服务器

1)提高访问速度
由于目标主机返回的数据会存放在代理服务器的硬盘中,因此下一次客户再访问相同的站点数据时,会直接从代理服务器的硬盘中读取,起到了缓存的作用,尤其对于热门站点能明显提高请求速度。
2)防火墙作用
由于所有的客户机请求都必须通过代理服务器访问远程站点,因此可在代理服务器上设限,过滤某些不安全信息。通过代理服务器访问不能访问的目标站点互联网上有许多开发的代理服务器,客户机在访问受限时,可通过不受限的代理服务器访问目标站点

2.nginx反向代理 VS nginx正向代理

2.1正向代理

正向代理(用于局域网共享上网)架设在客户机与目标主机之间,只用于代理内部网络对Internet的连接请求,客户机必须指定代理服务器,并将本来要直接发送到Web服务器上的http请求发送到代理服务器中。
也就是说,内网的客户机请求->通过正向代理到->互联网的web服务器
正向代理最大的特点是客户端非常明确要访问的服务器地址;服务器只清楚请求来自哪个代理服务器,而不清楚来自哪个具体的客户端;正向代理模式屏蔽或者隐藏了真实客户端信息。
在这里插入图片描述
nginx正向代理配置:
环境准备:
内网客户机172.24.8.105
nginx正向代理192.168.131.107(web服务器)
再添加一个仅主机的网卡172.24.8.100用于代理服务器的数据转发
步骤:
192.168.131.107:
1.开启路由转发功能:

[root@node1 ~]# vim /etc/sysctl.conf
net.ipv4.ip_forward=1
[root@node1 ~]# sysctl -p

2.配置nginx正向代理

[root@node1 ~]# cat /etc/nginx/conf.d/vhost.conf
server {	
	listen 8080;
	resolver 8.8.8.8;
	location / {
		proxy_pass http://$http_host$request_uri;
	}
}
[root@node1 ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@node1 ~]# nginx -s reload
[root@node1 ~]# netstat -lnutp | grep 8080
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      1867/nginx: master

172.24.8.105:测试客户机是否可以上网
在谷歌浏览器添加代理服务器地址:菜单->设置->高级->系统->打开计算机的代理设置
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
注:以上的配置只能访问 80 端口的网站,而不能访问https443端口的网站,现在的网站基本上都是https的。
要解决技能访问http80端口也能访问https443端口的网站,需要置两个SERVER节点,一个处理HTTP转发,另一个处理HTTPS转发,而客户端都通过HTTP来访问代理,通过访问代理不同的端口,来区分HTTP和HTTPS请求。
由于原生 nginx 只支持 http 正向代理,为了 nginx 支持 https 正向代理,可以打ngx_http_proxy_connect_module 补丁+ ssl 模块支持。
添加 https 代理模块。这里需要重新编译 nginx,需要查看当前 nginx 的版本和编译选项,然后去官网下载同版本的 nginx 源码进行重新编译。
下载模块 ngx_http_proxy_connect_module

git clone https://github.com/chobits/ngx_http_proxy_connect_module

打补丁,对 nginx 源码修改,这一步很重要,不然后面的 make 过不去

patch -d /root/nginx-1.15.12/ -p 1 < /root/ngx_http_proxy_connect_module/patch/proxy_connect_rewrite

在原有配置后追加模块,make 后注意不要 install

cd /root/nginx-1.15.12/
./configure --with-http_stub_status_module --with-http_ssl_module --with-file-
aio --with-http_realip_module --add-module=/root/ngx_http_proxy_connect_module/
make
mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak
cp /root/nginx-1.15.12/objs/nginx /usr/local/nginx/sbin/

配置文件如下,然后启动服务

# 正向代理上网
server {
  listen    38080;
  # 解析域名
  resolver   8.8.8.8;
  # ngx_http_proxy_connect_module
 proxy_connect;
  proxy_connect_allow       443 563;
  proxy_connect_connect_timeout 10s;
  proxy_connect_read_timeout   10s;
  proxy_connect_send_timeout   10s;
  location / {
    proxy_pass $scheme://$http_host$request_uri;
 }
}

2.2反向代理

反向代理架设在服务器端通过缓冲经常被请求的页面来缓解服务器的工作量,将客户机请求转发给内部网络上的目标服务器;并将从服务器上得到的结果返回给Internet上请求连接的客户端,此时代理服务器与目标主机一起对外表现为一个服务器。
也就是说,互联网的客户机请求->通过反向代理到->内网的web服务器
作用:隐藏了内部网络的拓扑结构,提高了安全性
在这里插入图片描述
nginx反向代理配置:
环境准备:操作在两台web服务器
192.168.131.108web服务器部署反向代理
192.168.131.107web服务器
步骤:
192.168.131.108:
1.部署反向代理

[root@node1 html]# cat /usr/local/nginx/conf/nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream; 
    sendfile        on;      
    keepalive_timeout  65;

   server {
        listen       80;
        server_name  test.org;
        location / {
            root   html;
            index  index.html index.htm;
			proxy_pass http://news.nginx.com;
        }

192.168.131.107:
2.配置web服务器

[root@manager html]# cat /etc/nginx/conf.d/vhost.conf
server {
    listen       80;
    server_name  news.nginx.com;

    location / {
        root   /usr/share/nginx/html/news/;
        index  index.html index.htm;
    }
} 

3.配置hosts文件

[root@node1 html]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.131.108 test.org
192.168.131.107 bbs.nginx.com blog.nginx.com news.nginx.com

测试:

#192.168.131.108
[root@node1 html]# curl test.org
news test page

在这里插入图片描述

3.nginx 负载均衡实战

实现 Nginx 负载均衡的组件说明:
在这里插入图片描述准备环境:
Web服务器结点192.168.131.108:根据不同的端口模范三台web服务器结点
web服务器代理结点192.168.131.107:把请求抛到负载均衡结点
步骤:
192.168.131.108
1.部署web服务器模范三台web服务器结点

[root@node1 html]# vim /usr/local/nginx/conf/nginx.conf

#user  nobody;
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

	server {
		listen 83;
		server_name www.web1.org;
		location / {
		root /usr/local/nginx/html/web1;
		index index.html index.htm;
	}
}
	server {
		listen 81;
		server_name www.web2.org;
		location / {
		root /usr/local/nginx/html/web2;
		index index.html index.htm;
	}
}
	server {
		listen 82;
		server_name www.web3.org;
		location / {
		root /usr/local/nginx/html/web3;
		index index.html index.htm;
	}
}
}
[root@node1 html]# systemctl restart nginx

192.168.131.107:
2.部署web服务器代理

[root@manager conf.d]# cat vhost.conf
upstream www_pools {
	server 192.168.131.108:83 weight=1;
	server 192.168.131.108:81 weight=1;
	server 192.168.131.108:82 weight=1;
}
server {
	listen 80;
	server_name nginx.org;
	location / {
		root /usr/share/nginx/html;
		proxy_pass http://www_pools;
	}
}
[root@manager conf.d]# systemctl restart nginx

测试:

C:\Windows\System32\drivers\etc\hosts
192.168.131.108 www.web1.org www.web2.org www.web3.org 
192.168.131.107 nginx.org

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

[root@manager conf.d]# for ((i=1;i<=6;i++));do curl nginx.org;done
web1
web2
web3
web1
web2
web3

3.1upstream的backup参数,则就访问不到该web服务器

注1:upstream 参数
在这里插入图片描述
backup参数:添加后,这台web服务器就访问不到了

[root@manager conf.d]# cat vhost.conf
upstream www_pools {
	server 192.168.131.108:83 weight=1;
	server 192.168.131.108:81 weight=1;
	server 192.168.131.108:82 weight=1 backup;
}
server {
	listen 80;
	server_name nginx.org;
	location / {
		root /usr/share/nginx/html;
		proxy_pass http://www_pools;
	}
}
[root@manager conf.d]# systemctl restart nginx
[root@manager conf.d]# for ((i=1;i<=6;i++));do curl nginx.org;done
web1
web2
web1
web2
web1
web2

3.2调度算法之ip_hash,提供持久连接的功能

注2:模块调度算法:
调度算法一般分为两类:
第一类为静态调度算法,即负载均衡器根据自身设定的规则进行分配,不需要考虑后端节点服务器的情况,例如:rr,wrr,ip_hash等都属于静态调度算法。
第二类为动态调度算法,即负载均衡器会根据后端节点的当前状态来决定是否分发请求,例如:连接数少的优先获得请求,响应时间短的优先获得请求。例如:least_conn,fair等都属于动态调度算法。
常用调动算法:
①. 定义轮询调度算法-rr-默认调度算法
②. 定义权重调度算法-wrr
③. 定义静态调度算法-ip_hash
该调度算法可以解决动态网页的session共享问题
④. 定义最小的连接数-least_conn
ip_hash调度算法:相当于持久连接。只有一台web服务器响应

[root@manager conf.d]# cat vhost.conf
upstream www_pools {
	ip_hash;
	server 192.168.131.108:83 weight=1;
	server 192.168.131.108:81 weight=1;
	server 192.168.131.108:82 weight=1;
}
server {
	listen 80;
	server_name nginx.org;
	location / {
		root /usr/share/nginx/html;
		proxy_pass http://www_pools;
	}
}
[root@manager conf.d]# systemctl restart nginx
[root@manager conf.d]# for ((i=1;i<=6;i++));do curl nginx.org;done
web3
web3
web3
web3
web3
web3

3.3添加某些参数,实现访问日志记录的是真实客户端的IP

在这里插入图片描述

注3:完成了反向代理WWW服务后,发现一个问题,节点服务器对应的WWW虚拟主机的访问日志的第一个字段记录的并不是客户端的IP,而是反向代理服务器的IP,最后一个字段也是“-”!

[root@web01 ~]# tail -2 /usr/share/nginx/html/www/logs/access_www.log
192.168.131.107 - - [06/Nov/2019:12:31:04 +0800] "GET / HTTP/1.0" 200 19 "-"
"curl/7.29.0" "-"
192.168.131.107 - - [06/Nov/2019:12:31:05 +0800] "GET / HTTP/1.0" 200 19 "-"
"curl/7.29.0" "-"

解决:
添加:proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;

[root@manager conf.d]# cat vhost.conf
upstream www_pools {
	#ip_hash;
	server 192.168.131.108:83 weight=1;
	server 192.168.131.108:81 weight=1;
	server 192.168.131.108:82 weight=1;
}
server {
	listen 80;
	server_name nginx.org;
	location / {
		root /usr/share/nginx/html;
		proxy_pass http://www_pools;
		proxy_set_header Host $host;
		proxy_set_header X-Forwarded-For $remote_addr;
	}
}
[root@manager conf.d]# systemctl restart nginx

测试:使用windows浏览器去访问,然后查看access.log里是否记录真实日志
在这里插入图片描述

[root@node1 html]# tail /usr/local/nginx/logs/access.log
192.168.131.107 - - [07/Aug/2020:23:57:05 +0800] "GET / HTTP/1.0" 200 5 "-" "curl/7.29.0"
192.168.131.107 - - [07/Aug/2020:23:57:05 +0800] "GET / HTTP/1.0" 200 5 "-" "curl/7.29.0"
192.168.131.107 - - [07/Aug/2020:23:57:05 +0800] "GET / HTTP/1.0" 200 5 "-" "curl/7.29.0"
192.168.131.107 - - [08/Aug/2020:00:09:16 +0800] "GET / HTTP/1.0" 200 5 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36"
192.168.131.107 - - [08/Aug/2020:00:09:16 +0800] "GET / HTTP/1.0" 200 5 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36"
192.168.131.107 - - [08/Aug/2020:00:09:16 +0800] "GET / HTTP/1.0" 200 5 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36"
192.168.131.107 - - [08/Aug/2020:00:09:16 +0800] "GET / HTTP/1.0" 200 5 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36"
192.168.131.107 - - [08/Aug/2020:00:09:17 +0800] "GET / HTTP/1.0" 200 5 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

骑着蜗牛追汤圆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值