3

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?

Janine Ohmer
  • 257
  • 1
  • 5
  • 8

2 Answers2

7

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;
Shane Madden
  • 114,520
  • 13
  • 181
  • 251
0

A workaround would be to change nginx thus:

   location / {
        proxy_read_timeout 120;
        proxy_set_header  X-Real-IP  $remote_addr;
        proxy_pass http://www.example.com:8100;
    }

Then modify /etc/hosts so www.example.com and example.com both point to 127.0.0.1 (internally). But Shane's answer is better, of course.

Eduardo Ivanec
  • 14,881
  • 1
  • 37
  • 43
  • Why make it complicated when the problem can be solved with Shane's one liner. Keep it simple. – Sameer Apr 15 '11 at 18:10
  • Of course, but I posted this anyway because this approach works for any proxy and Janine hadn't tested the other answer yet. – Eduardo Ivanec Apr 15 '11 at 18:14