Shashank Shekher Shashank Shekher - 1 year ago 83
Linux Question

How to read an HTTP header value in a CGI Bash script

I have a CGI Bash script
located on a server running Nginx. The script is called with the following command:

curl -s -D - -H "range: bytes=1-8" -H "Connection: close" -X GET http://server_ip/cgi-bin/

I need to fetch the value of the
request header within
. Please help me to figure out how can it be achieved.

Answer Source

HTTP headers are usually passed to CGI programs as environment variables. But it is not always the case.

Generally, the way you access the header values in a CGI program depends on how the Web server processes the headers. The headers may be modified, or even removed. For example, in an Nginx configuration, it is possible to pass the value of the range header via custom FastCGI parameter:

fastcgi_param RANGE $http_range;

It this case it is likely that the environment variable will be called RANGE, but it eventually depends on implementation of the protocol driver. The headers may be even dropped due to the server configuration. For example, the following Apache 2 configuration drops the range header when there are more than 5 ranges:

SetEnvIf Range (,.*?){5,} bad-range=1
RequestHeader unset Range env=bad-range

Thus, it is generally impossible to predict the name of the environment variable, and even whether it will be available in the CGI program.

However, if the header is available in the script, it will be available via an environment variable. You can find the exact name by examining the output of the env command.

The following should work with the default settings for Apache2:

#!/bin/bash -
printf '%s\n\n' 'Content-type: text/html'
printf '>>> %s <<< \n' "$HTTP_RANGE"
exit 0

Sample Output

HTTP/1.1 200 OK
Date: Thu, 10 Nov 2016 08:17:23 GMT
Server: Apache
Connection: close
Transfer-Encoding: chunked
Content-Type: text/html

>>> bytes=1-8 <<< 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download