Nginx:通过Cookie实现A/B测试
启动
Nginx配置
worker_processes 1;
error_log logs/error.log;
error_log logs/error.log notice;
error_log logs/error.log info;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
access_log logs/access.log;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
}
}
启动
进入nginx的安装目录直接双击运行nginx.exe就可以启动。
有没有起来可以使用tasklist命令进行查看。我使用的是cmder,命令和运行结果如下;
D:\nginx-1.14.2
λ tasklist | grep nginx
nginx.exe 3456 Console 4 7,056 K
nginx.exe 9508 Console 4 7,528 K
通过Cookie重设root
配置文件
server {
listen 80;
server_name guanjie.com;
location /index.html {
expires -1;
add_header Cache-Control no-cache;
add_header Pragma no-cache;
add_header Expires 0;
set $index_root html;
if ($cookie_greyFlag = 'grey') {
set $index_root grey;
}
root $index_root;
}
}
Nginx 文件配置
├─conf
├─contrib
│ ├─unicode2nginx
│ └─vim
│ ├─ftdetect
│ ├─ftplugin
│ ├─indent
│ └─syntax
├─grey
│ └─index.html
├─html
│ └─js
│ └─index.html
├─logs
└─temp
├─client_body_temp
├─fastcgi_temp
├─proxy_temp
├─scgi_temp
└─uwsgi_temp
index.html文件内容
html文件夹下index.html文件内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Productive Index</title>
</head>
<body>
<p>This is Productive User Index!!</p>
</body>
</html>
grey文件夹下index.html文件内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Grey Index</title>
</head>
<body>
<p>This is Grey User Index!</p>
</body>
</html>
测试
为guanjie.com
配置对应的host,在浏览器进行访问。使用下面的函数设置请求使用的cookie
function setCookie(key, val) {
document.cookie = key + "=" + val;
}
setCookie("greyFlag", "grey"); //灰度
setCookie("greyFlag", "nogrey"); //正式
设置不同的cookie我们可以看到不同的界面,从而实现A/B测试