没有设置主机头

I have a PHP script that primes my website cache.

I'm trying to bypass the Nginx frontend and grab the headers from the Apache backend.

The following example works (via command line) :

curl -I -H "Host: example.com" 127.0.0.1

However, when I try to do the same in PHP - it does not.

$headers = array("Host: example.com");
$url = "127.0.0.1";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt ($ch, CURLOPT_HEADER, true);
curl_setopt ($ch, CURLOPT_NOBODY, true);
curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
$ret = curl_exec ($ch);
curl_close ($ch);

echo "$ret";

This always returns the first website listed in my apache virtualhost files - not the website listed in the 'host' http headers.

Any idea why it works just fine via command line - but not in the php script?

I don't know if it is possible at all, however what I would try is to pass the URL at init:

$ch = curl_init($url);

And then not with curl_setopt. It's just a suggestion to test, no guarantee this helps. So more a lengthy comment.

You can also enable verbose mode and see what specifically curl sends for request headers, I have outlined this in an answer here: Bad Request. Connecting to sites via curl on host and system. This should show what is going on behind the curtain, very useful if you do not yet sniff the network traffic.

I think here is the answer.

"Do this instead:

$host = "www.example.com"; 
$url = "http://$host/"; 

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL, $url); 

"