具有多个“server_name”条目的 nginx“server”指令:总是第一个传递给 PHP 的 $_SERVER['SERVER_NAME']

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31479341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:27:40  来源:igfitidea点击:

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

phpnginxconfigurationfastcgi

提问by Paolo

My configuration file has a serverdirective block that begins with...

我的配置文件有一个server以...开头的指令块

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

但是 PHP$_SERVER['SERVER_NAME']总是返回 的第一个条目server_name,在这种情况下http://www.example1.com

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

所以我无法从 PHP 代码知道用户使用哪个域访问该站点。

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

有什么办法可以告诉nginx/fastcgi传递用于访问站点的真实域名吗?



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

到目前为止,我找到的唯一解决方案是server使用不同的server_name条目为每个域重复整个块,但显然我正在寻找更好的解决方案。

回答by Tan Hong Tat

Set SERVER_NAMEto use $hostin your fastcgi_paramsconfiguration.

设置SERVER_NAME$host在您的fastcgi_params配置中使用。

fastcgi_param   SERVER_NAME         $host;

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

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

回答by Sjon

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

这是有意的,正确的解决方案是$_SERVER['HTTP_HOST']在您的代码中使用。

You should interpret SERVER_NAMEas a verifiedserver-name, and HTTP_HOSTas user-input which can be modified quite easily, and thus shouldn't be trusted.

您应该将其解释SERVER_NAME经过验证的服务器名称,以及HTTP_HOST可以很容易修改的用户输入,因此不应被信任。