Nginx获取header自定义变量

nginx代理默认会把header中参数的 "_" 下划线去掉,所以后台服务器后就获取不到带"_"线的参数名。:

underscores_in_headers on; #该属性默认为off,表示如果header name中包含下划线,则忽略掉。

自定义header为X-Real-IP,通过第二个nginx获取该header时需要这样:

  • $http_x_real_ip; (一律采用小写,而且前面多了个http_)

Nginx向$_SERVER中添加变量

location ~ \.php$ {
try_files      $uri =404;
root           /www/wwwroot/app;
fastcgi_pass   127.0.0.1:9000;
fastcgi_index  index.php;
fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
fastcgi_param  MYENV 'DEV';  
include        fastcgi_params;
}

fastcgi_param  MYENV 'DEV';   #这里就向php 的$_SERVER 中增加了一个变量

通过php获取$_SERVER获取变量

"MYENV" => "DEV"

Nginx获取header自定义值添加到$_SERVER

自定义header的值为UserName=yyp,需要nginx获取该值后添加到$_SERVER中

nginx获取的key都需要换成小写,同时key的前面需要加上http_

location ~ \.php$ {
underscores_in_headers on;
try_files      $uri =404;
root           /www/wwwroot/app;
fastcgi_pass   127.0.0.1:9000;
fastcgi_index  index.php;
fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
fastcgi_param  UserNmae $http_username;  
include        fastcgi_params;
}

案例

nginx配置

    location ~ \.php?.*$ { 
        fastcgi_pass   unix:/tmp/php-cgi-56.sock;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name; 
        include        fastcgi_params; 
        fastcgi_param  TOKEN $http_username;  
        fastcgi_param  TOKEN88 $http_userpassword;  
        
    } 

页面配置

cat b.php  通过b页面获取设置的header的值
<html>
<head>
    <script language="php">
       echo "php is php.";
    </script>
 
</head>
<body>
<?php
  echo "<table border='1'>";
    foreach ($_SERVER as $key=>$value){
        echo "<tr>";
        echo "<td>$key</td>";
        echo "<td>$value</td>";
        echo "</tr>";
    }
    echo "</table>";
?>
</body>
</html>

通过curl命令修改header

curl 'http://192.168.2.84/b.php' -H 'username: yyp2' -H 'userpassword: 123' > a.html

结果显示
Nginx获取header,设置$_SERVER_php