17

我在一个 nginx conf 文件中有大约 1300 个虚拟主机。所有具有以下布局(它们在 vhost 文件中依次列出)。

现在我的问题是有时我的浏览器会将site2重定向到site1。出于某种原因,虽然域名不匹配。

看起来 nginx 总是重定向到 vhosts 文件中的第一个站点。

有人知道这个问题可能是什么吗?

server {
    listen   80;

    server_name site1.com;
    rewrite ^(.*) http://www.site1.com$1 permanent;
}

server {
    listen   80;

    root /srv/www/site/public_html/src/public/;
    error_log /srv/www/site/logs/error.log;
    index index.php;

   server_name www.site1.com;

    location / {
        if (!-e $request_filename) {
            rewrite ^.*$ /index.php last;
        }
    }

    location ~ .(php|phtml)$ {
        try_files $uri $uri/ /index.php;
        fastcgi_param SCRIPT_FILENAME /srv/www/site/public_html/src/public$fastcgi_script_name;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

server {
    listen   80;

    server_name site2.com;
    rewrite ^(.*) http://www.site2.com$1 permanent;
}

server {
    listen   80;

    root /srv/www/site/public_html/src/public/;
    error_log /srv/www/site/logs/error.log;
    index index.php;

   server_name www.site2.com;

    location / {
        if (!-e $request_filename) {
            rewrite ^.*$ /index.php last;
        }
    }

    location ~ .(php|phtml)$ {
        try_files $uri $uri/ /index.php;
        fastcgi_param SCRIPT_FILENAME /srv/www/site/public_html/src/public$fastcgi_script_name;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

编辑也许要提到的另一件事是,我每 2 分钟使用 nginx -s reload 重新加载所有这些虚拟主机。

在第一次测试中,重定向似乎只在重新加载时发生......要做更多测试,但这可能会有所帮助..

4

1 回答 1

19

参考(nginx如何处理请求): http: //nginx.org/en/docs/http/request_processing.html

在此配置中,nginx 仅测试请求的标头字段“Host”,以确定应将请求路由到哪个服务器。如果它的值不匹配任何服务器名称,或者请求根本不包含这个头域,那么 nginx 会将请求路由到这个端口的默认服务器。

默认服务器是第一个——这是 nginx 的标准默认行为

你能检查那些错误请求的主机头吗?

您还可以创建一个显式默认服务器来捕获所有这些错误请求,并将请求信息(即 $http_host)记录到不同的错误日志文件中以供调查。

server {
    listen       80  default_server;
    server_name  _;
    error_log /path/to/the/default_server_error.log;

    return       444;
}

[更新]正如您所做的那样nginx -s reload,您在该 nginx conf 文件中有这么多域,以下是可能的:

重新加载是这样的

使用新配置启动新工作进程,优雅关闭旧工作进程

所以老工人和新工人可以共存一段时间。例如,当您在配置文件中添加一个新的服务器块(带有新域名)时,在重新加载期间,新的工作人员将拥有新的域,而旧的则没有。当请求恰好由旧的工作进程发送时,它将被视为未知主机并由默认服务器提供服务。

你说它每2分钟完成一次。你能跑吗

ps aux |grep nginx

并检查每个工人运行了多长时间?如果超过 2 分钟,重新加载可能无法按预期工作。

于 2013-04-03T23:14:27.513 回答