DISQUS

Homo-Adminus Blog: Nginx With PHP As FastCGI Howto

  • BOLK · 3 years ago
    После компиляции у PHP 5.1.4 не появился ключ -b.
  • toivo · 3 years ago
    Грабли.
    1. PHP запущенный с ключем "-b" время от времени незаметно падает. Как решить не знаю.
    2. Для нормальной работы скриптов типа "Dumper" или других длинных скриптов можно использовать
    fastcgi_read_timeout 10m; например.

    Макс Тараненко.
  • andrewy kravchenko · 3 years ago
    Привет,

    Я с ним (nginx) первый раз столкнулся. Замучился уже с настройкой rewrite+php (fastcgi). Могли бы показать?
    Мне надо сдлелать "разброску" по поддоменам (это я уже решил) так, чтоб это нормально работало с PHP (это и есть проблема).

    Проблема заключается в том, что в ответ на http://SOME.localhost.ru/ я получаю то, что требуется, а в ответ на http://SOME.localhost.ru/index.php получаю сообщение "No input file specified", т.е. я неверно настроил реврайтинг.

    Вот мой конфиг:

    server {

    listen 127.0.0.1:80;
    server_name localhost.ru *.localhost.ru


    location / {
    root /home/www/data/public_html/;
    index index.php index.html index.htm;


    # перенаправление YYY.XXX.localhost.ru на XXX.localhost.ru
    if ($http_host ~ ^.+\.[^\.]+\.localhost\.ru.*$) {
    rewrite ^(.*)$ $http_host$1;
    rewrite ^.*\.([^\.]+)\.localhost\.ru(.*)$ http://$1.localhost.ru$2 permanent;
    break;
    }


    # отображение XXX.localhost.ru в пользовательские папки XXX
    if ($http_host ~ ^.*\.localhost\.ru.*$) {
    rewrite ^(.*)$ $http_host$1;
    rewrite ^(.+)\.localhost\.ru(.*)$ /ub$2 break;
    break;
    }


    }

    location ~ \.php$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /home/flybb/data/public_html$fastcgi_script_name;
    fastcgi_param QUERY_STRING $query_string;
    fastcgi_param REQUEST_METHOD $request_method;
    fastcgi_param CONTENT_TYPE $content_type;
    fastcgi_param CONTENT_LENGTH $content_length;
    }


    }
  • Sergey · 3 years ago
    Добрый день.
    Осмелюсь задать вопрос и расчитываю на помощь, так как не у кого больше спросить :(

    Есть виртуальный сервер, в котором нужно прописать alias - выглядит это так:

    location / {
    root /www/www2/www3/forum ;
    index index.php;
    }

    location ~ \.php$ {
    fastcgi_pass unix:/tmp/php4.3.0-fcgi.sock;
    #fastcgi_pass 127.0.0.1:9090;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /www/www2/www3/forum$fastcgi_script_name;
    fastcgi_param QUERY_STRING $query_string;
    }
    и нужно добавить алиас который будет обрабатываться PHP-шником:

    location /gallery/ {
    alias /www/www2/www3/4images/;
    index index.php;
    }

    И вот не получается :( Статику из алиаса отдаёт, а ПХП скрипты нет :(
    Подскажите что нужно сделать. Заранее благодарен.

    Вид сайта должен получиться таким:
    http://www.site.com/
    а с алисом
    http://www.site.com/gallery/
  • Scoundrel · 3 years ago
    А почему алиас, а не просто root?
  • Chris Carter · 3 years ago
    Hi, I am relitavely new to nginx and I was wondering how to add multiple servers/vhosts. DO I just add another server declaration?
  • Scoundrel · 3 years ago
    Yes, just add another server section with different hostname.
  • Chris Carter · 3 years ago
    Cool, thanks!
  • Sergey · 3 years ago
    а можно ли как то задавать отдельным виртуальным серверам разные значения php_flag?
  • Scoundrel · 3 years ago
    Я думаю, что только проксируя из них на отдельные fastcgi-сервера с разными конфигами.... насколько мне известно, php не умеет принимать такие параметры из fastcgi.
  • дедик · 3 years ago
    Форум IPB под fastcgi php не хочет показывать IP посетителя. Вместо него ставит -1
    Подскажите в чем может быть дело.
  • Scoundrel · 3 years ago
    Дело может юыть в том, что он пытается брать IP юзера из какого-то хитрого места... я вижу 2 варианта:
    1) Попатчить его
    2) Найти, как он это делает и попытаться передать ему этот IP нужным образом.
  • Ian · 3 years ago
    Is there a nginx mailing list or forum? I feel bad always asking you these questions before I try and switch our site from lighttpd to nginx.

    But on that note...

    The nginx site mentions "quick log rotation" but I can't seem to find anything on it. I pipe apache and lighttpd logs through cronolog right now. Can nginx do that and if so, what would the syntax be?
  • Scoundrel · 3 years ago
    2Ian: http://wiki.codemongers.com/ - great resource about Nginx.

    Nginx community is primarily Russian speaking now, so it can be hard to ask community some questions...

    But don't think, that there is no English-speaking community! It is there, but it is not so organized yet as Russian one is, so there is no active newsgroups or mailing lists dedicated to nginx. But you can as me here or via IM and I'll try to answer within my knowledge of nginx and English ;-)
  • mahesh mhatre · 2 years ago
    Could anyone tell me how to add multiple servers/vhosts?
  • dclau · 2 years ago
    Nginx seems very tempting/interesting piece of software. Does anybody know how it how it performs on dual/multiple processor machines?

    Regards, Clau
  • Scoundrel · 2 years ago
    2dclau: It performs really well because it has set of worker processes each of them implements connections multiplexing with asynchronous sockets and FSM. You really should try it.
  • dclau · 2 years ago
    I will. :)

    Regards, Clau
  • Korban · 2 years ago
    Ребята, помогите с решением проблемы.

    Переходим с Apache на Nginx, производительность возросла в Х-раз, ресурсов жрет ровно в 2 раза меньше, в общем все летает, но есть одна проблемка из-за которой перейти не можем.

    В Apache .htaccess есть правило
    RewriteCond %{REMOTE_ADDR} ^XXX.XXX.XXX.XXX
    RewriteRule ^(.*)folder/([0-9]*).gif$ http://othersite.com//$2.gif

    RewriteCond %{REMOTE_ADDR} !^XXX.XXX.XXX.XXX
    RewriteRule ^(.*)folder/([0-9]*).gif$ http://mainsite.com//$2.gif

    Помогите написать такие правила для Nginx

    Спасибо.
  • Scoundrel · 2 years ago
  • Jeremy · 2 years ago
    After the first time I launch my info.php for test, I have this message :
    "No input file specified."
    Could anybody help me ?

    Jeremy.
  • Guiturner · 2 years ago
    For Jeremy:

    That error means that the path at:

    fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;

    Doesn't point to your php files.

    Regards
  • popeye · 2 years ago
    во freebsd скрипт запуска php fcgi
    строчку
    EX="/bin/su -m -c \"$PHPFCGI -q -b $FCGIADDR:$FCGIPORT\" $USERID"

    надо заменить на
    EX="/bin/su -m $USERID -c \"$PHPFCGI -q -b $FCGIADDR:$FCGIPORT\""
  • alex · 2 years ago
    Скрипт для запуска php в fastcgi работает нормально на 5.1.6 и не работает на 5.2.1. Получаю Connection from disallowed IP в stderr от php и закрытие соединения. Убираю параметр -q и всё работает на 5.2.1
  • alex · 2 years ago
    Хотя ошибся
    установил FCGI_WEB_SERVER_ADDRS="127.0.0.1" и заработало.
  • Jeremy · 2 years ago
    Thanks ! It works :-)

    Relative path "html$fastcgi_script_name;" doesn't work...but...Absoulte path "/usr/local/nginx/html$fastcgi_script_name;" works

    Regards
  • John · 2 years ago
    Nginx - это конечно здорово, но очень узкоспециализировано...
    Кто-нить смог решить проблему использования файлов *.htc c этим сервером?
    Кто хочет по настоящему "устать" - вперед...
    Интересно, это вообще реально?
  • Макс Лапшин · 2 years ago
    А в чём проблема с .htc?
  • Mojtaba · 2 years ago
    Hi
    I installed nginx and php as you said but when I try to open a php file it displays:
    The page you are looking for is temporarily unavailable.
    Please try again later.

    Can you help me with that?
    Thanks
  • Doktor · 2 years ago
    А вот fcgi во всех ли версиях пхп есть?

    Очепяточку поправьте "версия примера нвходится".
  • Jeremy · 2 years ago
    Hello,

    I have some problems with rewrite rules.
    First, excuse me for my bad English...

    I have an htacces from Apache like :

    RewriteEngine on
    DirectoryIndex gabarit.php?contenu=itineraire
    RewriteCond %{REQUEST_URI} !temporaire\.htm
    RewriteRule ^([a-z-]*)\.htm$ gabarit\.php?contenu=$1 [L]
    RewriteRule ^galeries/$ gabarit\.php?contenu=accueil-galerie [L]
    RewriteRule ^galeries/([0-9]*)/([0-9]*)\.htm$ gabarit\.php?contenu=detail-galerie&categorie=$1&galerie=$2 [L]

    I want to translate it to Nginx rewrite rules

    Here, a piece of my conf that doesn't work :

    location /
    {
    index gabarit.php;
    root /home/work/jnbarak/current;

    rewrite ^/(.*)\.htm$ /gabarit.php?contenu=$1 last; # it works !
    rewrite ^/galeries/$ /gabarit\.php?contenu=accueil-galerie? last; # it doesn't work !
    rewrite ^/galeries/([0-9]*)/([0-9]*)\.htm$ /gabarit\.php?contenu=detail-galerie&categorie=$1&galerie=$2 last; # it doesn't work !
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$
    {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /home/work/jnbarak/current$fastcgi_script_name;
    include /usr/local/nginx/conf/fastcgi.conf;
    }


    When I try :

    http://my_domain.tld/galeries/

    I have the error :

    "No input file specified."

    When I try :

    http://my_domain.tld/galeries/1/5.htm

    I am redirect to :

    http://my_domain.tld/gabarit.php?contenu=accuei...


    Some one can help me please ?

    Good job with this blog and long life to Nginx !

    Jeremy.
  • Jeremy · 2 years ago
    Hello,

    I want to deleguate the rewrite rules of my vhosts to an other person who hasn't root privileges.
    With Apache, it's possible to declare a dynamic configuration file htaccess in each web repository. And it's not necessary to restart the server when file has changed.
    Is it possible to do it with Nginx ?

    Best regards.

    Jérémy.
  • Dmitry · 2 years ago
    To: toivo
    > 1. PHP запущенный с ключем “-b” время от времени незаметно падает. Как решить не знаю.

    Сталкнулся с такой же проблемой. Удалось решить?
  • Scoundrel · 2 years ago
    2Dmitry:

    > ## number of request before php-process
    > will be restarted
    > PHP_FCGI_MAX_REQUESTS=1000

    Вот оно - решение :-) Падает он незаметно именно после 1000 запросов в данном случае. Потому надо перезапускать или найти как отключить (может быть при 0 оно не будет его гасить).
  • Learn PHP · 2 years ago
    Excellent tutorial Scoundrel. keep them coming.
  • Rick · 2 years ago
    thanks
    There's a question I have to ask.
    My php scripts are in /var/www/my/,so I created a alias for them.
    Content:
    location /my/
    {
    alias /vaw/www/my/;
    }
    After running, I noted that the html files can be excuted properly,but the php files can not be found and excuted.Text from the server is "No input file specified".Please tell how to set this kind of alias.
    Forgive my pool English.
    By the way,the php scritps in /var/ww/html(my root document) can be excuted properly.
  • Larry Kluger · 2 years ago
    Hi,

    Thanks! Great post. Unfortunately, I'm seeing a nginx error: 2007/10/15 17:32:17 [error] 5093#0: *3381 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 69.2.2.2, server: www.forum.server.com, URL: "/index.php", upstream: "fastcgi://127.0.0.1:8888", host: "www.forum.server.com"

    I installed the latest php, v2.2.0

    Ideas much appreciated,

    Larry
  • Larry Kluger · 2 years ago
    Hello again,

    Solved the problem by enabling logging on php (see php.ini) and then sending error out to a file. (See last line of the php start-up script, above.) The error message from php was that FCGI_WEB_SERVER_ADDRS was not set correctly.

    Adding FCGI_WEB_SERVER_ADDRS="127.0.0.1" to the start-up script solved the problem.

    Also note that the php-cgi binary should be used, not the regular php binary.

    Regards,

    Larry
  • Lecactus · 2 years ago
    Поставил себе тоже этот nginx+fastcgi php5+mysql5+eaccelerator

    все вроде бы работает, но есть вопрос такой:

    у меня 5виртуальных хостов
    но пхп работает только если прописать путь аналогичный
    fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;

    где этот путь является путем до одно из хостов. т.е. если написать путь /корень/хост1

    все хосты расположены так

    корень - хост1
    корень - хост2
    и т.п.

    если задать в параметре путь к корню то пхп пытается обработать тот файл что лежит в нем...
  • Rick · 2 years ago
    please tell me how to solve the problem,I have waited for the answer for a month.Please.

    thanks
    There’s a question I have to ask.
    My php scripts are in /var/www/my/,so I created a alias for them.
    Content:
    location /my/
    {
    alias /vaw/www/my/;
    }
    After running, I noted that the html files can be excuted properly,but the php files can not be found and excuted.Text from the server is “No input file specified”.Please tell how to set this kind of alias.
    Forgive my pool English.
    By the way,the php scritps in /var/ww/html(my root document) can be excuted properly.
  • Alinaki · 2 years ago
    Кстати да, я до сих пор понять не мог, почему у меня к htc файлам доступ запрещен. А без них верстка под IE6 становится не особо... Кто-нибудь знает, как победить эту проблему? похоже, не у меня одного она.
  • sewerson · 2 years ago
    your article is nice but does not work. lots of people are experiencing the same error "No input file specified." - do you have a solution for that?
  • sewerson · 2 years ago
    solved! make sure that
    fastcgi_param SCRIPT_FILENAME
    points to the right directory where your script is located. this solved the issue for me!
  • dimian · 2 years ago
    sewerson - thank you for solve!!!
  • Erick · 1 year ago
    Please respond to this comment by also CCing me. Because you don't have other kind of subscription.

    Thank you for posting this. But I think it is a bit complex.

    1. What if I want to run PHP through nginx but without fastcgi (which is way too painful for anything beyond the basic PHP functionality).

    2. Also, in my Apache the "DefaultType" is PHP. So I have many programs without a ".php" configuration. In your example config, you tell nginx to serve php files based on the file-extension (.php). Can I tell nginx to serve php files based on "Type" and not the "File Extension"?

    Thanks!
  • e_nagual · 1 year ago
    Уважаемые подскажите!

    Скрипт запуска Fast CGI (который представлен в этой статье) - не полный, у него отсутствует нижняя часть!

    Подскажите пожалуйста , где взять этот скрипт полностью?

    Большое спасибо
  • garrotte · 1 year ago
    Здравствуйте Алексей..
    Если не затруднит, подскажите пожалуйста.. имеет-ли смысл играть с директивами буферизации (proxy_buffers, proxy_buffer_size) при проксировании на fastcgi.. ?
    Заранее благодарю..
  • Anton · 1 year ago
    Здраствуйте, у меня к вам вопрос, я сделал всё как вы описали в этой статье, но почему то через некоторое время nginx выдает bad gateway, в качестве сревера стоит spawn-fcgi , такое ощущение что cgi сервер коннекты намеренно отбрасывает, перелопатил весь конфиг nginx но проблемы так и не решил
  • donie · 1 year ago
    hello do you know how to add 1 alias that will affect to all vhost?
  • Denis · 1 year ago
    If you want to use alias + fastcgi, you could add something like this into config:

    location /gallery2-base/ {
    alias /usr/share/gallery2/;
    index index.php index.html index.htm;
    }

    location ~ /gallery2-base/.*\.php$ {
    if ($fastcgi_script_name ~ /gallery2-base(/.*\.php)$) {
    set $valid_fastcgi_script_name $1;
    }
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /usr/share/gallery2$valid_fastcgi_script_name;
    include /etc/nginx/fastcgi_params;
    }
  • zhito · 1 year ago
    спасибо за статью.
    очень полезно
  • йожег · 1 year ago
    Помогите передать бэкенду PHP заголовок запроса "If-Modified-Since", спасибо за статью, но мало чем помогло в моем случае.
  • _kT · 1 year ago
    Здравстуйте. У ngnix я заметил такой недостаток как то, что он делает буферизацию пост запросов, а в моих сайтах часто используюся аплоады прогресс бары и из - за этой буферизации скрипты полчуют в tmp уже полность загруженный файл, то есть поргресс бар стоит на нуле а птом сразу 100%

    Есть ли у ngnix какая - нид возможность отключить будеризацию пост запросос и сразу направлять их php
  • Макс Лапшин · 1 year ago
    Искренне рекомендую пользоваться swfupload
  • _kT · 1 year ago
    этот вариант только если в проекте допускаются флэшки. ЩАс пока у нас сделали так что к апачу можно пробиться вне ngnix по нестандартному порту и через него работаем с нашим аплоадером.
  • Макс Лапшин · 1 year ago
    У нас обычно nginx проксирует запросы к нескольким монгрелам, поэтому отдельный порт не укажешь.