一 nginx 安装
1、Nginx安装
- 获得软件
wget http://nginx.org/download/nginx-1.15.5.tar.gz -P /usr/src - 安装前准备
cd /usr/src
tar xf nginx-1.15.5.tar.gz
cd nginx-1.15.5
yum -y install gcc pcre-devel zlib zlib-devel - 配置
1)检查环境 是否 满足安装条件 依赖解决
2)指定安装方式 配置文件 命令文件 各种文件放哪里 开启模块功能【内
置模块 三方模块】
3)指定软件安装在那里
./configure --prefix=/usr/local/nginx - 编译 使用gcc将源码生成可执行程序
make -j4 - 安装
make install
2、相关目录
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”
3、Nginx启动
/usr/local/nginx/sbin/nginx
二 nginx配置
#nginx进程,一般设置为和cpu核数一样
worker_processes 4;
#错误日志存放目录
error_log /data1/logs/error.log crit;
#运行用户,默认即是nginx,可不设置
user nginx
#进程pid存放位置
pid /application/nginx/nginx.pid;
#Specifies the value for maximum file descriptors that can be opened by this process.
#最大文件打开数(连接),可设置为系统优化后的ulimit -HSn的结果
worker_rlimit_nofile 51200;
cpu亲和力配置,让不同的进程使用不同的cpu
worker_cpu_affinity 0001 0010 0100 1000 0001 00100100 1000;
#工作模式及连接数上限
events
{
use epoll; #epoll是多路复用IO(I/O Multiplexing)中的一种方式,但是仅用于linux2.6以上内核,可以大大提高nginx的性能
worker_connections 1024; #;单个后台worker process进程的最大并发链接数
}
###################################################
http
{
include mime.types; #文件扩展名与类型映射表
default_type application/octet-stream; #默认文件类型
# limit模块,可防范一定量的DDOS攻击
# 用来存储session会话的状态,如下是为session分配一个名为one的10M的内存存储区,限制了每秒只接受一个ip的一次请求 1r/s
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;
include mime.types;
default_type application/octet-stream;
#第三方模块lua防火墙
lua_need_request_body on;
#lua_shared_dict limit 50m;
lua_package_path "/application/nginx/conf/waf/?.lua";
init_by_lua_file "/application/nginx/conf/waf/init.lua";
access_by_lua_file "/application/nginx/conf/waf/access.lua";
#设定请求缓存
server_names_hash_bucket_size 128;
client_header_buffer_size 512k;
large_client_header_buffers 4 512k;
client_max_body_size 100m;
#隐藏响应header和错误通知中的版本号
server_tokens off;
#开启高效传输模式
sendfile on;
-------------------------------------------------------------------------------------------------
#激活tcp_nopush参数可以允许把httpresponse header和文件的开始放在一个文件里发布,
积极的作用是减少网络报文段的数量
tcp_nopush on;
#激活tcp_nodelay,内核会等待将更多的字节组成一个数据包,从而提高I/O性能
tcp_nodelay on;
--------------------------------------------------------------------
#FastCGI相关参数:为了改善网站性能:减少资源占用,提高访问速度
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
----------------------------------------------
#连接超时时间,单位是秒
keepalive_timeout 60;
#开启gzip压缩功能
gzip on;
#设置允许压缩的页面最小字节数,页面字节数从header头的Content-Length中获取。默认值是0,表示不管页面多大都进行压缩。建议设置成大于1K。如果小于1K可能会越压越大。
gzip_min_length 1k;
#压缩缓冲区大小。表示申请4个单位为16K的内存作为压缩结果流缓存,默认值是申请与原始数据大小相同的内存空间来存储gzip压缩结果。
gzip_buffers 4 16k;
#压缩版本(默认1.1,前端为squid2.5时使用1.0)用于设置识别HTTP协议版本,默认是1.1,目前大部分浏览器已经支持GZIP解压,使用默认即可。
gzip_http_version 1.0;
#压缩比率。用来指定GZIP压缩比,1压缩比最小,处理速度最快;9压缩比最大,传输速度快,但处理最慢,也比较消耗cpu资源。
gzip_comp_level 9;
#用来指定压缩的类型,“text/html”类型总是会被压缩
gzip_types text/plain application/x-javascript text/css application/xml;
#vary header支持。该选项可以让前端的缓存服务器缓存经过GZIP压缩的页面,例如用
Squid缓存经过Nginx压缩的数据。
gzip_vary off;
#开启ssi支持,默认是off
ssi on;
ssi_silent_errors on;
#设置日志模式
log_format access '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for';
#反向代理负载均衡设定部分
#upstream表示负载服务器池,定义名字为backend_server的服务器池
upstream backend_server {
server 10.254.244.20:81 weight=1 max_fails=2 fail_timeout=30s;
server 10.254.242.40:81 weight=1 max_fails=2 fail_timeout=30s;
server 10.254.245.19:81 weight=1 max_fails=2 fail_timeout=30s;
server 10.254.243.39:81 weight=1 max_fails=2 fail_timeout=30s;
#设置由 fail_timeout 定义的时间段内连接该主机的失败次数,以此来断定 fail_timeout 定义的时间段内该主机是否可用。默认情况下这个数值设置为 1。零值的话禁用这个数量的尝试。
设置在指定时间内连接到主机的失败次数,超过该次数该主机被认为不可用。
#这里是在30s内尝试2次失败即认为主机不可用!
}
###################
#基于域名的虚拟主机
server
{
#监听端口
listen 80;
server_name www.abc.com abc.com;
index index.html index.htm index.php; #首页排序
root /data0/abc; #站点根目录,即网站程序存放目录
error_page 500 502 404 /templates/kumi/phpcms/404.html; #错误页面
#伪静态 将www.abc.com/list....html的文件转发到index.php。。。
#rewrite ^/list-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /index.php?m=content&c=index&a=lists&catid=$1&types=$2&country=$3&language=$4&age=$5&startDate=$6&typeLetter=$7&type=$8&page=$9 last;
#location 标签,根目录下的.svn目录禁止访问
location ~ /.svn/ {
deny all;
}
location ~ \.php$
{ #符合php扩展名的请求调度到fcgi server
fastcgi_pass 127.0.0.1:9000; #抛给本机的9000端口
fastcgi_index index.php; #设定动态首页
include fcgi.conf;
}
allow 219.237.222.30 ; #允许访问的ip
allow 219.237.222.31 ;
allow 219.237.222.32 ;
allow 219.237.222.33 ;
allow 219.237.222.34 ;
allow 219.237.222.35 ;
allow 219.237.222.61 ;
allow 219.237.222.28 ;
deny all; #禁止其他ip访问
}
location ~ ^/admin.php
{
location ~ \.php$
{
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fcgi.conf;
}
allow 219.237.222.30 ;
allow 219.237.222.31 ;
allow 219.237.222.32 ;
allow 219.237.222.33 ;
allow 219.237.222.34 ;
allow 219.237.222.35 ;
allow 219.237.222.61;
allow 219.237.222.28;
deny all;
}
#将符合js,css文件的等设定expries缓存参数,要求浏览器缓存。
location~ .*\.(js|css)?$ {
expires 30d; #客户端缓存上述js,css数据30天
}
##add by 20140321#######nginx防sql注入##########
###start####
if ( $query_string ~* ".*[\;'\<\>].*" ){
return 444;
}
if ($query_string ~* ".*(insert|select|delete|update|count|\*|%|master|truncate|declare|\'|\;|and|or|\(|\)|exec).* ")
{
return 444;
}
if ($request_uri ~* "(cost\()|(concat\()") {
return 444;
}
if ($request_uri ~* "[+|(%20)]union[+|(%20)]") {
return 444;
}
if ($request_uri ~* "[+|(%20)]and[+|(%20)]") {
return 444;
}
if ($request_uri ~* "[+|(%20)]select[+|(%20)]") {
return 444;
}
set $block_file_injections 0;
if ($query_string ~ "[a-zA-Z0-9_]=(\.\.//?)+") {
set $block_file_injections 1;
}
if ($query_string ~ "[a-zA-Z0-9_]=/([a-z0-9_.]//?)+") {
set $block_file_injections 1;
}
if ($block_file_injections = 1) {
return 448;
}
set $block_common_exploits 0;
if ($query_string ~ "(<|%3C).*script.*(>|%3E)") {
set $block_common_exploits 1;
}
if ($query_string ~ "GLOBALS(=|\[|\%[0-9A-Z]{0,2})") {
set $block_common_exploits 1;
}
if ($query_string ~ "_REQUEST(=|\[|\%[0-9A-Z]{0,2})") {
set $block_common_exploits 1;
}
if ($query_string ~ "proc/self/environ") {
set $block_common_exploits 1;
}
if ($query_string ~ "mosConfig_[a-zA-Z_]{1,21}(=|\%3D)") {
set $block_common_exploits 1;
}
if ($query_string ~ "base64_(en|de)code\(.*\)") {
set $block_common_exploits 1;
}
if ($block_common_exploits = 1) {
return 444;
}
set $block_spam 0;
if ($query_string ~ "\b(ultram|unicauca|valium|viagra|vicodin|xanax|ypxaieo)\b") {
set $block_spam 1;
}
if ($query_string ~ "\b(erections|hoodia|huronriveracres|impotence|levitra|libido)\b") {
set $block_spam 1;
}
if ($query_string ~ "\b(ambien|blue\spill|cialis|cocaine|ejaculation|erectile)\b") {
set $block_spam 1;
}
if ($query_string ~ "\b(lipitor|phentermin|pro[sz]ac|sandyauer|tramadol|troyhamby)\b") {
set $block_spam 1;
}
if ($block_spam = 1) {
return 444;
}
set $block_user_agents 0;
if ($http_user_agent ~ "Wget") {
set $block_user_agents 1;
}
# Disable Akeeba Remote Control 2.5 and earlier
if ($http_user_agent ~ "Indy Library") {
set $block_user_agents 1;
}
# Common bandwidth hoggers and hacking tools.
if ($http_user_agent ~ "libwww-perl") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "GetRight") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "GetWeb!") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "Go!Zilla") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "Download Demon") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "Go-Ahead-Got-It") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "TurnitinBot") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "GrabNet") {
set $block_user_agents 1;
}
if ($block_user_agents = 1) {
return 444;
}
###end####
location ~ ^/list {
#如果后端的服务器返回502、504、执行超时等错误,自动将请求转发到upstream负载均衡池中的另一台服务器,实现故障转移。
proxy_next_upstream http_502 http_504 error timeout invalid_header;
proxy_cache cache_one;
#对不同的HTTP状态码设置不同的缓存时间
proxy_cache_valid 200 301 302 304 1d;
#proxy_cache_valid any 1d;
#以域名、URI、参数组合成Web缓存的Key值,Nginx根据Key值哈希,存储缓存内容到二级缓存目录内
proxy_cache_key $host$uri$is_args$args;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_ignore_headers "Cache-Control" "Expires" "Set-Cookie";
#proxy_ignore_headers Set-Cookie;
#proxy_hide_header Set-Cookie;
proxy_pass http://backend_server;
add_header Nginx-Cache "$upstream_cache_status from km";
expires 1d;
}
access_log /data1/logs/abc.com.log access; #nginx访问日志
}
-----------------------ssl(https)相关------------------------------------
server {
listen 13820; #监听端口
server_name localhost;
charset utf-8; #gbk,utf-8,gb2312,gb18030 可以实现多种编码识别
ssl on; #开启ssl
ssl_certificate /ls/app/nginx/conf/mgmtxiangqiankeys/server.crt; #服务的证书
ssl_certificate_key /ls/app/nginx/conf/mgmtxiangqiankeys/server.key; #服务端key
ssl_client_certificate /ls/app/nginx/conf/mgmtxiangqiankeys/ca.crt; #客户端证书
ssl_session_timeout 5m; #session超时时间
ssl_verify_client on; # 开户客户端证书验证
ssl_protocols SSLv2 SSLv3 TLSv1; #允许SSL协议
ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; #加密算法
ssl_prefer_server_ciphers on; #启动加密算法
access_log /lw/logs/nginx/dataadmin.test.com.ssl.access.log access ; #日志格式及日志存放路径
error_log /lw/logs/nginx/dataadmin.test.com.ssl.error.log; #错误日志存放路径
}
-------------------------------------------------------------------------
}
三 nginx详细功能实现
3.1 默认网站
1、默认网站
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
2、访问控制
location /a {
allow 192.168.1.0/24;
deny all;
#return 404;
return http://www.jd.com;
}
3、登陆验证
location /c {
auth_basic "登陆验证";
auth_basic_user_file /etc/nginx/htpasswd;
}
4、日志管理
Nginx访问日志主要有两个参数控制
log_format #用来定义记录日志的格式(可以定义多种日志格式,取不同名字即
可)
access_log #用来指定日至文件的路径及使用的何种日志格式记录日志
access_log logs/access.log main;
log_format格式变量:
$remote_addr #记录访问网站的客户端地址
$remote_user #远程客户端用户名
$time_local #记录访问时间与时区
$request #用户的http请求起始行信息
$status #http状态码,记录请求返回的状态码,例如:200、301、404等
$body_bytes_sent #服务器发送给客户端的响应body字节数
$http_referer #记录此次请求是从哪个连接访问过来的,可以根据该参数进
行防盗链设置。
$http_user_agent #记录客户端访问信息,例如:浏览器、手机客户端等
$http_x_forwarded_for #当前端有代理服务器时,设置web节点记录客户端
地址的配置,此参数生效的前提是代理服务器也要进行相关的x_forwarded_for设 置
案例
自定义一个json格式的访问日志
log_format main_json '{"@timestamp":"$time_local",'
'"client_ip": "$remote_addr",'
'"request": "$request",'
'"status": "$status",'
'"bytes": "$body_bytes_sent",'
'"x_forwarded": "$http_x_forwarded_for",'
'"referer": "$http_referer"'
'}';
access_log logs/access_json.log main_json;
5、防盗链
location /images/ {
alias /data/images/;
valid_referers none blocked *.ayitula.com;
if ($invalid_referer) {
rewrite ^/ http://www.ayitula.com/daolian.gif;
#return 403;
}}
6、日志截断
mv access.log access.log.0
killall -USR1 `cat master.nginx.pid`
sleep 1
gzip access.log.0
3.2 虚拟主机
就是把一台物理服务器划分成多个“虚拟”的服务器,每一个虚拟主机都可以有独
立的域名和独立的目录
同时发布两个网站:
DocumentRoot /usr/local/nginx/html/web1
DocumentRoot /usr/local/nginx/html/web2
1、基于IP的虚拟主机
实现条件
1) 两个IP
2)DR 存在
3)索引页 index.html
#每个网站都需要一个IP
#缺点 需要多个IP 如果是公网IP 每个IP都需要付费
server {
listen 192.168.10.42:80;
location / {
root html/web1;
index index.html index.htm index.php;
} }
server {
listen 192.168.10.52:80;
location / {
root html/web2;
index index.html index.htm;
} }
2、基于端口的虚拟主机
#只需要一个IP
#缺点 端口你是无法告诉公网用户 无法适用于公网客户 适合内部用户
基于端口
server {
listen 80;
#server_name www.abc.com;
location / {
root html/web1;
index index.html index.htm index.php;
} }
server {
listen 8080;
#server_name www.abc.com;
location / {
root html/web2;
index index.html index.htm;
} }
3、基于域名的虚拟主机
一个网站必然有一个域名
基于域名
server {
listen 80;
server_name www.abc.com;
location / {
root html/web1;
index index.html index.htm index.php;
} }
server {
listen 80;
server_name www.cbd.com;
location / {
root html/web2;
index index.html index.htm;
} }
3.3 反向代理
代理服务器,客户机在发送请求时,不会直接发送给目的主机,而是先发送给代理
服务器,代理服务接受客户机请求之后,再向主机发出,并接收目的主机返回的数
据,存放在代理服务器的硬盘中,再发送给客户机。
client mac http://192.168.10.42
反代 Nginx 42
业务机器 book.ayitula.com http://118.190.209.153:4000/
location / {
index index.php index.html index.htm; #定义首页索引文件的名称
proxy_pass http://mysvr ;#请求转向mysvr 定义的服务器列表
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m; #允许客户端请求的最大单文件字节数
client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数,
proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间(代理连接超时)
proxy_send_timeout 90; #后端服务器数据回传时间(代理发送超时)
proxy_read_timeout 90; #连接成功后,后端服务器响应时间(代理接收超时)
proxy_buffer_size 4k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小
proxy_buffers 4 32k; #proxy_buffers缓冲区,网页平均在32k以下的话,这样设置
proxy_busy_buffers_size 64k; #高负荷下缓冲大小(proxy_buffers*2)
proxy_temp_file_write_size 64k; #设定缓存文件夹大小,大于这个值,将从upstream服务器传
}
3.4 限速
限流(rate limiting)是NGINX众多特性中最有用的,也是经常容易被误解和错误
配置的,特性之一。该特性可以限制某个用户在一个给定时间段内能够产生的HTTP
请求数。请求可以简单到就是一个对于主页的GET请求或者一个登陆表格的POST
请求。
限流也可以用于安全目的上,比如减慢暴力密码破解攻击。通过限制进来的请求速
率,并且(结合日志)标记出目标URLs来帮助防范DDoS攻击。一般地说,限流是
用在保护上游应用服务器不被在同一时刻的大量用户请求湮没。
算法思想是:
水(请求)从上方倒入水桶,从水桶下方流出(被处理);
来不及流出的水存在水桶中(缓冲),以固定速率流出;
水桶满后水溢出(丢弃)。
这个算法的核心是:缓存请求、匀速处理、多余的请求直接丢弃。
相比漏桶算法,令牌桶算法不同之处在于它不但有一只“桶”,还有个队列,
这个桶是用来存放令牌的,队列才是用来存放请求的。
Nginx官方版本限制IP的连接和并发分别有两个模块:
limit_req_zone 用来限制单位时间内的请求数,即速率限制,采用的漏桶算法"leaky bucket"。
limit_req_conn 用来限制同一时间连接数,即并发限制。
limit_req_zone 参数配置
Syntax: limit_req zone=name [burst=number] [nodelay];
Default: —
Context: http, server, location
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
#基于IP对下载速率做限制 限制每秒处理1次请求,对突发超过5个以后的请求放
入缓存区
http {
limit_req_zone $binary_remote_addr zone=baism:10m rate=1r/s;
server {
location /abc {
limit_req zone=baism burst=5 nodelay;
}
}
limit_req_zone $binary_remote_addr zone=baism:10m rate=1r/s;
第一个参数:$binary_remote_addr 表示通过remote_addr这个标识来做限制,“binary_”的目的是缩写内存占用量,是限制同一客户端ip地址。
第二个参数:zone=baism:10m表示生成一个大小为10M,名字为one的内存区域,用来存储访问的频次信息.
第三个参数:rate=1r/s表示允许相同标识的客户端的访问频次,这里限制的是每秒1次,还可以有比如30r/m的。
limit_req zone=baism burst=5 nodelay;
第一个参数:zone=baism 设置使用哪个配置区域来做限制,与上面limit_req_zone 里的name对应。
第二个参数:burst=5,重点说明一下这个配置,burst爆发的意思,这个配置的意思是设置一个大小为5的缓冲区当有大量请求(爆发)过来时,超过了访问频次限制的请求可以先放到这个缓冲区内。
第三个参数:nodelay,如果设置,超过访问频次而且缓冲区也满了的时候就会直接返回503,如果没有设置,则所有请求会等待排队。
#基于IP做连接限制 限制同一IP并发为1 下载速度为100K
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
location /abc {
limit_conn addr 1;
limit_rate 100k;
}
}
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
#基于IP做连接限制 限制同一IP并发为1 下载速度为100K
limit_conn_zone $binary_remote_addr zone=addr:10m;
#基于IP对下载速率做限制 限制每秒处理1次请求,对突发超过5个以后的请求放
入缓存区
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
location /abc {
limit_req zone=one burst=5 nodelay;
limit_conn addr 1;
limit_rate 100k;
}
}
}
3.5 URL重定向
URL 模块语法
# 1) set 设置变量
# 2) if 负责语句中的判断
# 3) return 返回返回值或URL
# 4) break 终止后续的rewrite规则
# 5) rewrite 重定向URL
# set指令 自定义变量
# Syntax:
# set $variable value;
# Default:
# —
# Context:
# server, location, if
将http://www.ayitula.com 重写为 http://www.ayitula.com/baism
location / {
set $name baism;
rewrite ^(.*)$ http://www.ayitula.com/$name;
}
if 指令 负责判断
Syntax:
if (condition) { ... }
Default:
—
Context:
server, location
location / {
root html;
index index.html index.htm;
if ($http_user_agent ~* 'Chrome') {
break;
return 403;
#return http://www.jd.com;
} }
#模糊匹配 ~匹配 !~不匹配 ~* 不区分大小写的匹配
#精确匹配 = !=
return 指令 定义返回数据
Syntax: return code [text];
return code URL;
return URL;
Default: —
Context: server, location, if
location / {
root html;
index index.html index.htm;
if ($http_user_agent ~* 'Chrome') {
return 403;
#return http://www.jd.com;
}
}
break 指令 停止执行当前虚拟主机的后续rewrite指令集
Syntax: break;
Default:—
Context:server, location, if
location / {
root html;
index index.html index.htm;
if ($http_user_agent ~* 'Chrome') {
break;
return 403;
}
}
rewrite <regex> <replacement> [flag];
关键字 正则 替代内容 flag标记
flag:
last #本条规则匹配完成后,继续向下匹配新的location URI规则
break #本条规则匹配完成即终止,不再匹配后面的任何规则
redirect #返回302临时重定向,浏览器地址会显示跳转后的URL地址
permanent #返回301永久重定向,浏览器地址栏会显示跳转后的URL地址
3.6 域名跳转
www.ayitula.com 重写为 www.jd.com
server {
listen 80;
server_name www.ayitula.com;
location / {
rewrite ^/$ http://www.jd.com permanent ;
}
}
注意:
重定向就是将网页自动转向重定向
301永久性重定向:新网址完全继承旧网址,旧网址的排名等完全清零
301重定向是网页更改地址后对搜索引擎友好的最好方法,只要不是暂时搬移
的情况,都建议使用301来做转址。
302临时性重定向:对旧网址没有影响,但新网址不会有排名
搜索引擎会抓取新的内容而保留旧的网址
break 类似临时重定向
根据用户浏览器重写访问目录
如果是chrome浏览器 就将 http://192.168.10.42/$URI 重写为
http://http://192.168.10.42/chrome/$URI
实现 步骤
1)URL重写
2)请求转给本机location
location / {
.....
if ($http_user_agent ~* 'chrome'){
#^ 以什么开头 ^a
#$ 以什么结尾 c$
#. 除了回车以外的任意一个字符
#* 前面的字符可以出现多次或者不出现
#更多内容看正则表达式 re
rewrite ^(.*)$ /chrome/$1 last;
}
location /chrome {
root html ;
index index.html;
}
}
url重写后,马上发起一个新的请求,再次进入server块,重试location匹配,超过
10次匹配不到报500错误,地址栏url不变
last 一般出现在server或if中
数据包走向 client-->nginx nginx告诉客户端让服务器的新地址(真实服务器),
客户端收到后再去找服务器 client--->server
3.7 优化
3.7.1 并发优化
#nginx进程,一般设置为和cpu核数一样
worker_processes 4;
#错误日志存放目录
error_log /data1/logs/error.log crit;
#运行用户,默认即是nginx,可不设置
user nginx
#进程pid存放位置
pid /application/nginx/nginx.pid;
#工作模式及连接数上限
events
{
use epoll; #epoll是多路复用IO(I/O Multiplexing)中的一种方式,但是仅用于linux2.6以上内核,可以大大提高nginx的性能
worker_connections 1024; #;单个后台worker process进程的最大并发链接数
}
3.7.2 长连接
#长连接的超时和连接数上限
keepalive_timeout 0; # 0代表关闭
#keepalive_timeout 100;
#keepalive_requests 8192;
3.7.3 压缩
gzip on;
gzip_proxied any;
gzip_min_length 1k;
gzip_buffers 4 8k;
gzip_comp_level 6;
gzip_types text/plain text/css application/x-javascript application/javascript
application/xml;
# 开启gzip
gzip off;
# 启用gzip压缩的最小文件,小于设置值的文件将不会压缩
gzip_min_length 1k;
# gzip 压缩级别,1-9,数字越大压缩的越好,也越占用CPU时间,后面会有详细说明
gzip_comp_level 1;
# 进行压缩的文件类型。javascript有多种形式。其中的值可以在 mime.types 文件中找到。
gzip_types text/plain application/javascript application/x-javascript
text/css application/xml text/javascript application/x-httpd-php
image/jpeg image/gif image/png application/vnd.ms-fontobject font/ttf
font/opentype font/x-woff image/svg+xml;
# 是否在http header中添加Vary: Accept-Encoding,建议开启
gzip_vary on;
# 禁用IE 6 gzip
gzip_disable "MSIE [1-6]\.";
# 设置压缩所需要的缓冲区大小
gzip_buffers 32 4k;
# 设置gzip压缩针对的HTTP协议版本
gzip_http_version 1.0;
#找大文件
find /usr/share/ -type f -size +1M
3.7.4 客户端缓存
针对图片进行缓存
location ~* \.(png|gif)$ {
expires 1h;
}
测试 浏览器刷新 以Chrome为例
ctrl+f5 清空本地缓存从服务器拿数据
F5或者 点击 浏览器的刷新图标 优先从本地找 然后 去找服务器核对信息
是否一致 一致 返回304 从本地那数据
回车 从本地缓存拿数据
3.8 集群
upstream module
nginx的upstream⽬前⽀持4种⽅式的分配
1、轮询(默认)
每个请求按时间顺序逐⼀分配到不同的后端服务器,如果后端服务器down掉,能⾃动剔除。
2、weight
指定轮询⼏率,weight和访问⽐率成正⽐,⽤于后端服务器性能不均的情况。
3、ip_hash
每个请求按访问ip的hash结果分配,这样每个访客固定访问⼀个后端服务器,可以解决session的问题。
4、fair(第三⽅)
按后端服务器的响应时间来分配请求,响应时间短的优先分配。
5、url_hash(第三⽅)
按访问url的hash结果来分配请求,使每个url定向到同⼀个后端服务器,后端服务器为缓存时⽐较有效。
每个设备的状态设置为:
1.down 表示单前的server暂时不参与负载
2.weight 默认为1.weight越⼤,负载的权重就越⼤。
3.max_fails :允许请求失败的次数默认为1.当超过最⼤次数时,返回proxy_next_upstream 模块定义的错误
4.fail_timeout:失败超时时间,在连接Server时,如果在超时时间之内超过max_fails指定的失败次数,会认为在fail_timeout时间内Server不可⽤。默认为10s。
5.backup: 其它所有的⾮backup机器down或者忙的时候,请求backup机器。所以这台机器压⼒会最轻。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
nginx 分发器设置
默认采⽤RR算法,如果想采⽤其他算法,如ip_hash类似于LVS sh,例⼦
upstream apache {
ip_hash;
server 192.168.10.42;
server 192.168.10.43;
}
server {
listen 80;
server_name www.abc.com;
location / {
proxy_pass http://apache;
}
}
ip_hash算法能够保证来⾃同样源地址的请求,都分发到同⼀台主机
url_hash
http://ip/a.html
需要⾃⼰重新编译nginx
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
基于权重
upstream web {
server 192.168.10.42 weight=1;
server 192.168.10.43 weight=2;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://web;
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
基于http协议主机头的分发
http {
upstream web1 {
server 192.168.10.42;
}
server {
listen 80;
server_name www.web1.com;
location / {
proxy_pass http://web1;
}
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
基于语⾔的分发
要求各位完成php,html分发的基础上实现负载均衡
http {
upstream php {
server 192.168.10.42;
}
upstream html {
server 192.168.10.43;
}
server {
location ~* \.php$ {
proxy_pass http://php;
}
}
location ~* \.html$ {
proxy_pass http://html;
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
基于浏览器分发
upstream elinks { server 192.168.10.42; }
upstream chrome { server 192.168.10.43; }
upstream any { server 192.168.10.42:81; }
server {
listen 80;
server_name www.web1.com;
location / {
proxy_pass http://any;
if ( $http_user_agent ~* Elinks ) {
proxy_pass http://elinks;
}
if ( $http_user_agent ~* chrome ) {
proxy_pass http://chrome;
}
}
}
思考如果其他浏览器呢? 去访问/tmp/186⽂件夹下的⽹站。 elinks浏览器去访问245
firefox访问246
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
http://192.168.10.40/a/b/c/index.php http://192.168.10.42
基于源地址分发(类似于ACL DNS)
编译
./configure --with-http_geoip_module
upstream bj.server {
server 192.168.10.42;
}
upstream sh.server {
server 192.168.10.43;
}
upstream default.server {
server 192.168.10.42:81;
}
geo $geo {
default default;
192.168.10.241/32 bj;
192.168.10.242/32 sh;
}
location / {
proxy_pass http://$geo.server$request_uri;
}