Nginx – With Nginx proxying to Apache, real hostname is lost

apache-2.2hostnamenginx

I have a situation with a number of websites sharing a single IP address. I have nginx accepting requests and passing them on to Apache, which actually serves the sites. I know that Apache isn't really needed here, but it's set up this way for historical reasons and I'd rather not change it if I don't have to.

The way things are set up, nginx accepts a request for example.com and passes it on to Apache like so:

server {
    listen       80;
    server_name example.com www.example.com;

    access_log  /var/log/nginx/example.log;
    error_log  /var/log/nginx/example.log;

    location / {
        proxy_read_timeout 120;
        proxy_set_header  X-Real-IP  $remote_addr;
        proxy_pass http://localhost:8100;
    }
}

In httpd.conf, we have

<VirtualHost localhost:8100>
    ServerName www.example.com
    ServerAlias example.com
    Options Indexes
    DocumentRoot /export/sites/example/live
    ServerAdmin info@example.net
</VirtualHost>

Everything has worked fine up to now, but I've added a PHP script (not my own) to the site and it is not able to get the correct hostname. Either $_SERVER["HTTP_HOST"] and/or $_SERVER['SERVER_NAME'] are returning localhost:8100 instead of example.com.

Is it possible to set this up so that PHP will get the right hostname?

Best Answer

By default, it sends the host spec from the proxy_pass line. You can override this by throwing this config in there, forcing the Host: header to contain the same as sent by the client:

proxy_set_header Host $host;