szs 发表于 2016-12-25 08:11:13

nginx working with header

working with header
  从哪写起呢,需求吧。
请求:https://header.test.ipinyou.com:7443/ ; 
1. nginx 加入:
     location / {
        proxy_set_header      Host $host:$server_port;
        proxy_set_header      X-Real-IP $remote_addr;
        proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass   http://127.0.0.1:81;
     }
    则:后端机器能拿到请求来源ip,请求host,port信息。
2. 获取head页面
    <html>    <body>
    <?php
        $arr = getallheaders();
            foreach ($arr as $item => $content){
                    echo "<font color=\"blue\"><b>$item</b></font>  => <font color=\"red\">\"$content\"</font></br>";
            }
    ?>
    </body>    </html>
    返回结果:
Host => "header.test.ipinyou.com:7443"
X-Real-IP => "192.168.1.1"
X-Forwarded-For => "192.168.1.1"
Connection => "close"
User-Agent => "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0"
Accept => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
Accept-Language => "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3"
Accept-Encoding => "gzip, deflate"
Cookie => "PYID=CBCC_81x6Ck; jsType=1; sessionId=D49Ard8ia4PR"               
  
3. 设置header,host,server_port
        proxy_set_header      Host $host;
        proxy_set_header      port $server_port;
   结果:
        Host => "header.test.ipinyou.com"
port => "7443"
 4. 自定义header
        使用modify header add on 设置  
            True-Client-IP   "testip"
            User-Agent     SonyEricsson e8000
            Host        "abcdef"
        nginx中设置:           
            proxy_set_header      Host $host;
            proxy_set_header      test2 'abc';
            proxy_set_header      test $http_true_client_ip;
    结果:
        Host => ""abcdef""
        port => "7443"
        test2 => "abc"
        test => "testip"
        X-Real-IP => "10.1.2.223"
        X-Forwarded-For => "10.1.2.223"
        Connection => "close"
        User-Agent => "SonyEricsson e8000"
        Accept => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
        Accept-Language => "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3"
        Accept-Encoding => "gzip, deflate"
        Cookie => "PYID=CBCC_81x6Ck; jsType=1; sessionId=D49Ard8ia4PR"
        True-Client-IP => "testip"
    发现捕捉到了自定义的 true_client_ip
5.更多自定义header
    当我们配置了
        underscores_in_headers on;  【使用字段:http, server  是否允许在header的字段中带下划线】
    之后,发现所有的自定义header都能被捕捉到。比如
        请求加入header:any_para   any_para_value
        proxy_set_header      any_para $http_any_para_value;
        得到:
                any_para => "any_para_value"
6. 写入响应头信息:
                header('myhost:phpserver');
    =>     myhost   phpserver
7. nginx全局变量
    http://www.cnblogs.com/AloneSword/archive/2011/12/10/2283483.html
页: [1]
查看完整版本: nginx working with header