$_SERVER['SERVER_NAME'] returns nginx reverse proxy port/name

Andy Affleck asked:

I am running WordPress under the following configuration:

Varnish (Port 80) -> nginx (Port 8080)

This is all working great except when some plugin or other tries to get my server name using $_SERVER['SERVER_NAME']. When that happens, it is getting back _:8080 as my server name and port. This is what the nginx config has:

server {
listen 8080;
server_name _;

What I need it to return is domain.com but if I change the nginx config, obviously, it stops listening on the port it needs to be (8080) (but changing the server_name works fine).

How can I have nginx listen on 8080 but have $_SERVER['SERVER_NAME'] return the correct port (or rather, not append the wrong port)?


My answer:

_:8080 is the correct value for $_SERVER['SERVER_NAME'] in this configuration. It’s explicitly defined to return the value of server_name. From the documentation:

The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.

It sounds like you are looking for $_SERVER['HTTP_HOST']. Note that you also need to have not configured Varnish to alter the Host: request header.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.