Laziness: curl Host Header

1 minute read

For some reason, I can never remember the right command line option for setting the Host HTTP header with curl. It’s actually something I need to do fairly regularly, it comes up testing server configurations before making changes to DNS. Say server.example.com is going to have a virthost configuration for www.example.net, but it’s DNS hasn’t been setup/changed to point the server. What you need to do, is connect to server.example.com and tell it you are looking for www.example.net. That’s what the HTTP Host header does, and with curl it looks like:

curl --header 'Host: www.example.net' http://server.example.com

You think I’d remember that.

Somehow, I don’t. And besides, that’s pretty verbose and it’s well know than I’m lazy. So, instead I created a BASH function and a TCSH alias hcurl, which I call like:

hcurl www.example.net http://server.example.com

Obviously, the first argument becomes the host for the header and the second is the URL.

The function looks like:

function hcurl() { curl --header "Host: $1" ${@:2} ;}

The ${@:2} is the magic here. We want to grab the first argument for the host, and pass everything else on to curl. This allows us to pass additional arguments, for example:

hcurl www.example.net --silent http://server.example.com

With BASH, $@ is all of the arguments passed to the function. The rest of the syntax is BASH’s slice syntax. Slice in BASH is one-indexed so ${@:2} says “give me a slice of the array starting at the second position”. The first argument is easily grabbed from $1.

For TCSH, we use an alias:

alias hcurl 'curl --header "Host: \!^" \!:2-$'

In this case !^ is the first argument (which can also be written as !:1) and !:2-$ means the second through the last arguments.

Maybe you remember the syntax, but if you don’t, or just what something a little lest verbose, you now have the tools.

Tags:

Updated:

Comments