LinuxForum.Fans
Тема

Nginx + cgi

Автор: XliN 15 сообщений 2276 просмотров
#160763

Возможно ли? В инете видел только перенаправление CGI скриптов на apache, который сидит на другом порту.

#160860

гугли php-cgi+nginx

#160994

Да гуглил уже. У меня прекрасно работает nginx+php-fpm http://mgkb1.dyndns.org/phpinfo.php
Мне нужно научить его открывать CGI скрипты. Посоветуйте минималистический httpd сервер, который можно использовать чисто для CGI. На него перенаправлять.

Вот с чем у меня собран nginx

Показать
'./configure' '--build=i686-redhat-linux-gnu' '--host=i686-redhat-linux-gnu' '--target=i386-redhat-linux-gnu' '--program-prefix=' '--prefix=/usr' '--exec-prefix=/usr' '--bindir=/usr/bin' '--sbindir=/usr/sbin' '--sysconfdir=/etc' '--datadir=/usr/share' '--includedir=/usr/include' '--libdir=/usr/lib' '--libexecdir=/usr/libexec' '--localstatedir=/var' '--sharedstatedir=/usr/com' '--mandir=/usr/share/man' '--infodir=/usr/share/info' '--cache-file=../config.cache' '--with-libdir=lib' '--with-config-file-path=/etc' '--with-config-file-scan-dir=/etc/php.d' '--disable-debug' '--with-pic' '--disable-rpath' '--without-pear' '--with-bz2' '--with-exec-dir=/usr/bin' '--with-freetype-dir=/usr' '--with-png-dir=/usr' '--with-xpm-dir=/usr' '--enable-gd-native-ttf' '--with-t1lib=/usr' '--without-gdbm' '--with-gettext' '--with-gmp' '--with-iconv' '--with-jpeg-dir=/usr' '--with-openssl' '--with-pcre-regex=/usr' '--with-zlib' '--with-layout=GNU' '--enable-exif' '--enable-ftp' '--enable-magic-quotes' '--enable-sockets' '--enable-sysvsem' '--enable-sysvshm' '--enable-sysvmsg' '--with-kerberos' '--enable-ucd-snmp-hack' '--enable-shmop' '--enable-calendar' '--without-mime-magic' '--without-sqlite' '--with-libxml-dir=/usr' '--enable-xml' '--with-system-tzdata' '--enable-force-cgi-redirect' '--enable-pcntl' '--with-imap=shared' '--with-imap-ssl' '--enable-mbstring=shared' '--enable-mbregex' '--with-ncurses=shared' '--with-gd=shared' '--enable-bcmath=shared' '--enable-dba=shared' '--with-db4=/usr' '--with-xmlrpc=shared' '--with-ldap=shared' '--with-ldap-sasl' '--with-mysql=shared,/usr' '--with-mysqli=shared,/usr/bin/mysql_config' '--enable-dom=shared' '--with-pgsql=shared' '--enable-wddx=shared' '--with-snmp=shared,/usr' '--enable-soap=shared' '--with-xsl=shared,/usr' '--enable-xmlreader=shared' '--enable-xmlwriter=shared' '--with-curl=shared,/usr' '--enable-fastcgi' '--enable-pdo=shared' '--with-pdo-odbc=shared,unixODBC,/usr' '--with-pdo-mysql=shared,/usr' '--with-pdo-pgsql=shared,/usr' '--with-pdo-sqlite=shared,/usr' '--with-pdo-dblib=shared,/usr' '--enable-json=shared' '--enable-zip=shared' '--with-readline' '--enable-dbase=shared' '--with-pspell=shared' '--with-mcrypt=shared,/usr' '--with-mhash=shared,/usr' '--with-tidy=shared,/usr' '--with-mssql=shared,/usr' '--enable-sysvmsg=shared' '--enable-sysvshm=shared' '--enable-sysvsem=shared' '--enable-posix=shared' '--with-unixODBC=shared,/usr' '--with-recode=shared,/usr' '--with-libevent=shared' '--with-fpm' '--with-fpm-bin=/usr/bin/php-cgi' '--with-fpm-port=9000' '--with-fpm-conf=/etc/php-fpm.conf' '--with-fpm-log=/var/log/php-fpm.log' '--with-fpm-pid=/var/run/php-fpm.pid' '--with-fpm-user=nobody' '--with-fpm-group=nobody'
#161053

Не работает. Тем более в приведенной хавтушке куча файлов, которых у меня нет и пути разные.
У меня не Debian.
Вот мои конфиги

Показать
text
[root@ldap html]# cat /etc/nginx/nginx.conf
user  nginx;
worker_processes  2;

error_log logs/error.log; pid logs/nginx.pid;

events { worker_connections 1024; }

http { include /etc/nginx/mime.types; default_type application/octet-stream;

log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';

access_log logs/access.log main; sendfile on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/vhosts/*.conf; }

Показать
text
[root@ldap html]# cat /etc/nginx/vhosts/default.conf
server {
    listen 80;
    server_name mgkb1.local;
location / {
    root /var/www/html;
    index index.php index.htm index.html;
    autoindex off;
    if (!-e $request_filename) {
        rewrite (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$ /index.php last;
        }
    }
location /nod32 {
    alias /var/www/html/nod32;
    autoindex on;
    allow all;
}
location /nginx_status {
    stub_status on;
    access_log off;
    allow all;
    }
location /munin {
    alias   /var/www/html/munin;
    autoindex on;
#   auth_basic "Munin data. Please login";
#   auth_basic_user_file /etc/munin/.passwd;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
    root   /usr/share/nginx/html;
    }

#location ~ \.php$ { # root /var/www/html; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /var/www/html$fastcgi_script_name; # include fastcgi_params;

location ~ .php$ { root /var/www/html; fastcgi_pass 127.0.0.1:9000; fastcgi_split_path_info ^(.+\.php)(.*)$; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /var/www/html$fastcgi_script_name; include fastcgi_params; fastcgi_param QUERY_STRING $query_string; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_intercept_errors on; fastcgi_ignore_client_abort off; fastcgi_connect_timeout 60; fastcgi_send_timeout 180; fastcgi_read_timeout 180; fastcgi_buffer_size 128k; fastcgi_buffers 4 256k; fastcgi_busy_buffers_size 256k; fastcgi_temp_file_write_size 256k; } location ~ /\.ht { deny all; } }

В корне сайта создал файл hello.cgi

text
#!/usr/bin/perl

print "Content-type: text/html\n\n";

print <<END_HTML; <html> <head></head> <body>Hello, World!</body> </html>

#161055

--=XliN=--, там для nginx 1.0.0.1 - пути не могут быть разными если это debian squeeze и репозиторий dotdeb, и сорри cgi там не прикручен...

#161056
newzenon написал:
и сорри cgi там не прикручен...

Вот и я про тоже )) Это можно реализовать только путем перенаправления выполнения CGI скрипта на другой веб сервер. Например на Apache, но я не хочу его ставить. Может есть какой маленький, совсем маленький?

#161057

--=XliN=--, я тоже озадачился по поводу cgi, вот например http://vkuzne.su/viewtopic.php?p=11019 - только там для nginx 0.7. А даунгрейд себе делать не буду.

#161058
newzenon написал:
А даунгрейд себе делать не буду.

Я тоже не хочу, в том то и дело, но CGI все равно хочется прикрутить.
Вот http://wiki.nginx.org/SimpleCGI Это не то?

#161534

--=XliN=--, оно. Еще немного другой вариант: http://anick.ru/blog/perl-fastcgi/
Скажи, а тебе зачем именно nginx? И зачем именно в стэндэлоун режиме?
Есть же куча вариантов без костылей- lighttpd, cherokee, все это в сочетании в виде фронт-энд/бэк-энд архитектуры, с инжниксом впереди в виде проксика-статикоотдателя.

#161550
Denlookh написал:
Скажи, а тебе зачем именно nginx? И зачем именно в стэндэлоун режиме?

Сервер у меня больно слабенький ))) И крутится на нем много служб ))

#161556

--=XliN=--, так что lighttpd, что cherokee в стэндэлоун режиме чуть тяжелее, но без костылей, а реврс-проксировниее оба могут :))

#189361

Короче опят ломал голову как cgi/perl прикрутить к nginx, проштудировал почти всё что ест тут http://wiki.nginx.org/Configuration
Получилось запустить на сокете fcgiwrap, скрипт запуска:

text
#!/usr/bin/perl
 
use strict;
use warnings FATAL => qw( all );
 
use IO::Socket::UNIX;
 
my $bin_path = '/usr/local/bin/fcgiwrap';
my $socket_path = $ARGV[0] || '/tmp/cgi.sock';
my $num_children = $ARGV[1] || 1;
 
close STDIN;
 
unlink $socket_path;
my $socket = IO::Socket::UNIX->new(
    Local => $socket_path,
    Listen => 100,
);
 
die "Cannot create socket at $socket_path: $!\n" unless $socket;
 
for (1 .. $num_children) {
    my $pid = fork;
    die "Cannot fork: $!" unless defined $pid;
    next if $pid;
 
    exec $bin_path;
    die "Failed to exec $bin_path: $!\n";
}

http://wiki.nginx.org/Fcgiwrap

Вставка для конфига nginx в виртуальном хосте:

text
location ~ ^/cgi-bin/.*\.cgi$ {
 fastcgi_pass unix:/tmp/cgi.sock;
 fastcgi_read_timeout 5m;
 fastcgi_index index.cgi;
 #
 # You may copy and paste the lines under or use include directive
 # include /etc/nginx/nginx-fcgi.conf;
 # In this example all is in one file
 #
 fastcgi_param SCRIPT_FILENAME $document_root$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;
 fastcgi_param GATEWAY_INTERFACE CGI/1.1;
 fastcgi_param SERVER_SOFTWARE nginx;
 fastcgi_param SCRIPT_NAME $fastcgi_script_name;
 fastcgi_param REQUEST_URI $request_uri;
 fastcgi_param DOCUMENT_URI $document_uri;
 fastcgi_param DOCUMENT_ROOT $document_root;
 fastcgi_param SERVER_PROTOCOL $server_protocol;
 fastcgi_param REMOTE_ADDR $remote_addr;
 fastcgi_param REMOTE_PORT $remote_port;
 fastcgi_param SERVER_ADDR $server_addr;
 fastcgi_param SERVER_PORT $server_port;
 fastcgi_param SERVER_NAME $server_name;
} 

Всё равно cgi не проглатывает. :(

Пока нашёл только один вариант - проксировать perl/cgi запросы на легкий mini-httpd.
Конфиг /etc/mini-httpd.conf

text
port=9001
user=www-data
data_dir=/var/www/site.ru
START=1
text
location ~ \.pl$ {
        root   /var/www/site.ru/cgi-bin;
        gzip off;
        proxy_pass    http://127.0.0.1:9001;

set $referer $http_referer; proxy_set_header Referer $referer; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host localhost:9001; proxy_set_header REQUEST_METHOD $request_method; proxy_set_header REMOTE_USER $remote_user; proxy_set_header REMOTE_ADDR $remote_addr; proxy_set_header SERVER_NAME localhost; proxy_set_header SERVER_PORT 9001; proxy_set_header HTTP_COOKIE $http_cookie; }

#189933
--=XliN=-- написал:
Сервер у меня больно слабенький ))) И крутится на нем много служб ))

Apache2 бэкендом много нагрузки не даст, особенно если использовать его только
для PHP, FastCGI и прочего, а через nginx отдавать всю статику.
А вообще, чем не устраивает lighttpd, он вроде тоже умеет CGI?
По крайней мере я прикручивал на него такое.

#189955

mdma, у меня уже больше спортивный интерес - как к nginx прикрутить cgi/perl, потому как вроде можно, бэкендом понятно - любой apache/lighttpd/mini-httpd подойдёт.
И разобраться со всеми этими модулями до конца не плохо бы, ну хотя бы с основными - кто и что делает, а то так по примерам, да по наитию:
Вот сейчас стоят:

text
php-fpm - этот понятно что делает.
cli-php
cgi-php
fcgiwrap
uwsgi
scgi

по идее cgi-php...
Как-то понимания до конца нет.
Вариант с проксированием из примеров понравился: http://wiki.nginx.org/ThttpdCGI

Войдите или зарегистрируйтесь, чтобы ответить.