Shashank Shekher Shashank Shekher - 22 days ago 15
Linux Question

How to read http headers value in a CGI bash script

I have a CGI bash script hw.sh located on a server and running on Nginx, which is getting executed using curl request:

curl -s -D - -H "range: bytes=1-8" -H "Connection: close" -X GET http://server_ip/cgi-bin/hw.sh?path=/some/path/to/data/


Now I need to fetch the value of the range header provided in the above curl request in my script
hw.sh
. Please let me know how can this be achieved.

Answer

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://apache-test.local/cgi-bin/test.sh?sdfdsf' 
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 <<< 
Comments