Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx "server" directive with multiple "server_name" entries: always first one is passed to PHP's $_SERVER['SERVER_NAME']

My configuration file has a server directive block that begins with...

server {     server_name www.example1.com www.example2.com www.example3.com; 

...in order to allow the site to be accessed with different domain names.

However PHP's $_SERVER['SERVER_NAME'] always returns the first entry of server_name, in this case http://www.example1.com

So I have no way from the PHP code to know which domain the user used to access the site.

Is there any way to tell nginx/fastcgi to pass the real domain name used to access the site?


The only solution I've found so far is to repeat the entire server block for each domain with a distinct server_name entry but obviously I'm looking for a better one.

like image 342
Paolo Avatar asked Jul 17 '15 15:07

Paolo


People also ask

What is server_name _ in nginx?

server { listen 80; server_name example.org www.example.org ""; ... } If no server_name is defined in a server block then nginx uses the empty name as the server name. nginx versions up to 0.8. 48 used the machine's hostname as the server name in this case. If a server name is defined as “ $hostname ” (0.9.

Does order matter in nginx config?

Yes, it does and totally depends on different directives specified within the different context supported by Nginx.

How does nginx route requests?

In this configuration nginx tests only the request's header field “Host” to determine which server the request should be routed to. If its value does not match any server name, or the request does not contain this header field at all, then nginx will route the request to the default server for this port.

How do I run multiple ports on nginx?

To make Nginx Listen on multiple ports for a single virtual host file, you can add multiple listen directives. If you want to make Nginx listen for different virtual hosts on different ports, you can use different ports in listen directive in different virtual host files. It's that easy!


2 Answers

Set SERVER_NAME to use $host in your fastcgi_params configuration.

fastcgi_param   SERVER_NAME         $host; 

Source: http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_param

like image 121
Tan Hong Tat Avatar answered Sep 22 '22 17:09

Tan Hong Tat


This is intended and the proper solution is to use $_SERVER['HTTP_HOST'] in your code instead.

You should interpret SERVER_NAME as a verified server-name, and HTTP_HOST as user-input which can be modified quite easily, and thus shouldn't be trusted.

like image 38
Sjon Avatar answered Sep 19 '22 17:09

Sjon