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测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值