4

Добрый день, коллеги! Не выходит настроить правильный редирект средствами php.

UPD: 21/10/2016 Вынес поддомен на который должна быть переадресация в отдельный конфиг nginx и отдельный пул php-fpm. Не помогло.

Конфиг nginx основного домена: domain.conf:

server {
    server_name  www.domain.ru;
    rewrite ^(.*) http://domain.ru$1 permanent;
}
server {
        listen 80;
        root /var/www/folder/public;

        index index.html index.htm index.php;

        server_name anotherdomain.ru subdomain2.domain.ru domain.ru;


        location ~ \.php$ {
            # root /var/www

                try_files $uri =404;
                fastcgi_keep_conn on;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME $request_filename;
                include /etc/nginx/fastcgi_params;
        }

        location / {
                try_files $uri $uri/ /index.php?q=$uri&$args;
        }

        location ~ /\.ht {
           deny all;
        }
}

Конфиг nginx поддомена:

subdomain.conf:

server {
        listen 80;
        root /var/www/folder/public;

        index index.html index.htm index.php;

        server_name subdomain.domain.ru;
        gzip on;
        gzip_disable "msie6";
        gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript;


        location ~ \.php$ {
            # root /var/www

                try_files $uri =404;
                fastcgi_keep_conn on;
                fastcgi_pass unix:/var/run/php5-fpm-subdomain.sock;
                #fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME $request_filename;
                include /etc/nginx/fastcgi_params;
        }

        location / {
                try_files $uri $uri/ /index.php?q=$uri&$args;
        }

        location ~ /\.ht {
           deny all;
        }
}

При таком коде:

<?php
header('Location:http://subdomain.domain.ru/');
exit;
?>

В ответ получаю:

[root@svm]# curl -I http://domain.ru/indexfile.php
HTTP/1.1 302 Moved Temporarily
Connection: close
Date: Mon, 17 Oct 2016 13:57:59 GMT
Location: http://domain.ru/
Content-Type: text/html; charset=UTF-8
Server: nginx/1.4.6 (Ubuntu)

Но при этом, в консоли отладки firefox вижу такой Url Запроса: http://domain.ru/subdomain.domain.ru

А при таком коде:

<?php
header('Location:http://subdomain2.domain.ru/');
exit;
?>

Прилетает это:

[root@svm]# curl -I http://domain.ru/indexfile2.php
HTTP/1.1 302 Moved Temporarily
Connection: close
Date: Mon, 17 Oct 2016 13:57:59 GMT
Location: http://subdomain2.domain.ru/
Content-Type: text/html; charset=UTF-8
Server: nginx/1.4.6 (Ubuntu)

Для одного конкретного поддомена не присваивается новый заголовок с location. В чём может быть проблема и как её исправить?

Наблюдение: Если в Location: указывать uri без http (То есть просто //subdomain.domain.ru, то перенаправление работает. Почему? Как исправить?

Интересный факт - Добавил в файл несколько произвольных заголовков и их вывод: "print_r(headers_list());". Судя по всему, php правильно выставляет headers, но они либо не применяются, либо их переписывает nginx:

[root@svm]# curl -v http://domain.ru/indexfile.php
* About to connect() to 4cio.ru port 80 (#0)
*   Trying 11.11.11.11...
* Connected to domain.ru (11.11.11.11) port 80 (#0)
> GET /indexfile.php HTTP/1.1
> User-Agent: curl/7.29.0
> Host: domain.ru
> Accept: /
>
< HTTP/1.1 302 Moved Temporarily
< Connection: Keep-Alive
< Transfer-Encoding: chunked
< Expires: Mon, 26 Jul 2666 05:00:00 GMT
< Date: Tue, 18 Oct 2016 14:46:44 GMT
< Location: **http://domain.ru** - Ну вот откуда он берётся?
< Content-Type: text/html; charset=UTF-8
< Server: nginx/1.4.6 (Ubuntu)
< Cache-Control: no-cache
<
Array
(
    [0] => Expires: Mon, 26 Jul 2666 05:00:00 GMT
    [1] => Cache-Control: no-cache
    [2] => Location: http://subdomain.domain.ru
)

UPD 2: 21.10.2016 Добавил логи nginx в debug-режиме:

Лог очень большой. Сравнил два лога- один для поддомена на который переадресация выполяется нормально, второй для поддомена на который переадресация не выполняется. В обоих случаях, nginx получает новый location при первой обработке php-файла. Ниже предоставлены выдержки с того момента, как они начинают отличаться:

Лог для не работающего поддомена:

http fastcgi sent end request
pipe write downstream: 1
pipe write downstream done
event timer: 61, old: 1477057711592, new: 1477057711593
http upstream exit: 0000000000000000
finalize http upstream request: 0
finalize http fastcgi request
free rr peer 1 0
close http upstream connection: 61
free: 000000000240DFA0, unused: 48
event timer del: 61: 1477057711592
reusable connection: 0
http upstream temp fd: -1
http output filter "/indexfile.php?"
http copy filter: "/indexfile.php?"
image filter
xslt filter body
http postpone filter "/indexfile.php?" 00007FFF3BF1A200
http chunk: 0
write old buf t:1 f:0 000000000249A7E8, pos 000000000249A7E8, size: 274 file: 0, size: 0
write new buf t:0 f:0 0000000000000000, pos 00000000004AA3DA, size: 5 file: 0, size: 0
http write filter: l:1 f:0 s:279
http write filter limit 0
writev: 279
http write filter 0000000000000000
http copy filter: 0 "/indexfile.php?"
http finalize request: 0, "/indexfile.php?" a:1, c:1
set http keepalive handler
http close request
http log handler
free: 000000000249AA20
free: 0000000002487340, unused: 8
free: 0000000002499A10, unused: 8
free: 0000000002409890, unused: 3556
free: 00000000024B1630
hc free: 0000000000000000 0
hc busy: 0000000000000000 0
tcp_nodelay
reusable connection: 1
event timer add: 60: 65000:1477057716593
post event 00000000024E0FA0
delete posted event 00000000024E0FA0
http keepalive handler
malloc: 00000000024B1630:1024
recv: fd:60 -1 of 1024
recv() not ready (11: Resource temporarily unavailable)
free: 00000000024B1630
post event 00000000024E0FA0
post event 00000000024F47B0
delete posted event 00000000024F47B0
http empty handler
delete posted event 00000000024E0FA0
http keepalive handler
malloc: 00000000024B1630:1024
recv: fd:60 329 of 1024
reusable connection: 0
posix_memalign: 0000000002487340:4096 @16
event timer del: 60: 1477057716593
http process request line
http request line: "GET / HTTP/1.1"
http uri: "/"
http args: ""
http exten: ""
posix_memalign: 0000000002499A10:4096 @16
http process request header line
http header: "Reverse-Via: FF-SRV"
http header: "Host: domain.ru"  ------Вот здесь должен быть subdomain.domain.ru
http header: "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0"
http header: "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
http header: "Accept-Language: en-US,ru-RU;q=0.8,ru;q=0.5,en;q=0.3"
http header: "DNT: 1"
http header: "Upgrade-Insecure-Requests: 1"
http header: "Connection: Keep-Alive"
http header done

Лог для работающего поддомена:

http fastcgi sent end request
posix_memalign: 00000000024B2620:4096 @16
pipe write downstream: 1
pipe write downstream done
event timer: 55, old: 1477057946320, new: 1477057946320
http upstream exit: 0000000000000000
finalize http upstream request: 0
finalize http fastcgi request
free rr peer 1 0
close http upstream connection: 55
free: 0000000002413EC0, unused: 48
event timer del: 55: 1477057946320
reusable connection: 0
http upstream temp fd: -1
http output filter "/indexfile.php?"
http copy filter: "/indexfile.php?"
image filter
xslt filter body
http postpone filter "/indexfile.php?" 00007FFF3BF1A200
http chunk: 0
write old buf t:1 f:0 000000000249C4B0, pos 000000000249C4B0, size: 270 file: 0, size: 0
write new buf t:0 f:0 0000000000000000, pos 00000000004AA3DA, size: 5 file: 0, size: 0
http write filter: l:1 f:0 s:275
http write filter limit 0
writev: 275
http write filter 0000000000000000
http copy filter: 0 "/indexfile.php?"
http finalize request: 0, "/indexfile.php?" a:1, c:1
set http keepalive handler
http close request
http log handler
free: 000000000240A000
free: 00000000025096F0, unused: 8
free: 000000000249B6E0, unused: 8
free: 00000000024B2620, unused: 3572
free: 0000000002488790
hc free: 0000000000000000 0
hc busy: 0000000000000000 0
tcp_nodelay
reusable connection: 1
event timer add: 54: 65000:1477057951320
post event 00000000024E0030
delete posted event 00000000024E0030
http keepalive handler
malloc: 0000000002488790:1024
recv: fd:54 -1 of 1024
recv() not ready (11: Resource temporarily unavailable)
free: 0000000002488790
delete posted event 00000000024F3840
http empty handler
accept: 22.22.22.22 fd:55
event timer add: 55: 60000:1477057946388
reusable connection: 1
epoll add event: fd:55 op:1 ev:80000001
post event 00000000024E1BD0
delete posted event 00000000024E1BD0
http wait request handler
posix_memalign: 00000000024888A0:256 @16
malloc: 00000000024889B0:1024
recv: fd:55 336 of 1024
reusable connection: 0
posix_memalign: 00000000025096F0:4096 @16
http process request line
http request line: "GET / HTTP/1.1"
http uri: "/"
http args: ""
http exten: ""
posix_memalign: 000000000249B6E0:4096 @16
http process request header line
http header: "Reverse-Via: FF-SRV"
http header: "Host: subdomain2.domain.ru"
http header: "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0"
http header: "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
http header: "Accept-Language: en-US,ru-RU;q=0.8,ru;q=0.5,en;q=0.3"
http header: "DNT: 1"
http header: "Upgrade-Insecure-Requests: 1"
http header: "Connection: Keep-Alive"
http header done

UPD 3: 24/10/2016 Наблюдение

Ели я размещаю файлик с переадресацией в subdomain2.domain.ru, то перенаправление на subdomain.domain.ru работает без проблем.

12
  • Возможно, стоит написать пробел после "Location:"? 19 окт 2016 в 16:10
  • Не имеет значения, к сожалению 19 окт 2016 в 16:12
  • //localhost - будет работать для http / https прозрачно перенаправляя правильно в зависимости от начального типа соединения http->http https->https. Поэтому моя догадка, для subdomain.domain.ru где то настроено перенаправление на https поэтому через http://... не работает, а с //... работает.
    – E_p
    19 окт 2016 в 16:33
  • Увы, нет. Такого перенаправления нет ни в конфиге nginx, ни в коде. 19 окт 2016 в 16:35
  • Тогда один вариант, включить логирование у nginx и смотреть логи.
    – E_p
    19 окт 2016 в 16:37

2 ответа 2

5

Коллеги, проблема решена.

Проблема оказалась вообще не в nginx.

ПЕМКИС, как это часто и бывает. Оказывается, на стороне Заказчика стоит прозрачный TMG, о чём не сообщили. В этом TMG было включено некорректное правило с изменением заголовков. Было включено "Подставлять действительный заголовок вместо запрошенного" для зоны domain.ru

p.s. ПЕМКИС = Проблема Есть Между Клавиатурой И Стулом

-3

Попробуйте:

rewrite ^(.*) http://domain.ru$request_uri permanent;
2
  • Прошу пояснить, в какую секцию Вы предполагаете это поместить и какую роль это будет выполнять? Если я правильно понимаю, то это правило будет перенаправлять все запросы адресованные на домены из конфига nginx на domain.ru/запрошеная_страница. Что мне это даёт? 19 окт 2016 в 19:21
  • Постарайтесь писать более развернутые ответы. Поясните, на чем основано ваше утверждение? 20 окт 2016 в 11:05

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.