웹사이트 검색

Gentoo LEMP에 FcgiWrap 설치 및 Perl, Ruby 및 Bash 동적 언어 활성화


이 튜토리얼은 젠투에 LEMP 설치에 대한 이전 튜토리얼과 엄격하게 관련되어 있으며 Fcgiwrap 게이트웨이를 통해 Perl, Bash 또는 Ruby와 같은 동적 스크립팅 언어를 활성화하고 Nginx 가상 호스트 구성 파일을 편집하는 것과 같은 다른 서버 확장 문제를 처리합니다. .pl, .rb.cgi 스크립트를 사용하여 동적 콘텐츠를 제공합니다.

요구사항

  1. 젠투에 설치된 LEMP 스택 - https://linux-console.net/install-lemp-in-gentoo-linux/

1단계: 젠투 LEMP에서 FCGIWRAP 활성화

Fcgiwrap은 Perl, Bash 또는 Ruby 스크립트와 같은 다른 동적 스크립팅 언어를 처리하는 Nginx FastCGI 공통 게이트웨이 인터페이스의 일부이며 TCP 또는 TCP를 통해 Nginx에서 받은 요청을 처리하여 작동합니다. Unix 소켓은 독립적인 방식으로 생성된 결과를 Nginx로 다시 반환하며, Nginx는 응답을 다시 최종 클라이언트로 전달합니다.

1. 먼저 다음 명령을 사용하여 Gentoo Linux에 FCcgiwrap 프로세스를 설치해 보겠습니다.

emerge --ask www-misc/fcgiwrap

2. 기본적으로 Fcgiwrap 패키지는 젠투에서 프로세스를 관리하기 위한 init 스크립트를 제공하지 않습니다. 패키지를 컴파일하고 설치한 후 세 가지 접근 방식, 즉 Unix 도메인 소켓을 사용하여 프로세스를 시작하거나 로컬 를 사용하여 Fcgiwrap 프로세스를 관리하는 데 도움이 되는 다음 init 스크립트를 만듭니다. b>TCP 소켓 또는 두 가지를 동시에 사용합니다.

TCP 소켓 스크립트 사용

다음 파일 내용으로 /etc/init.d/ 경로에 init 파일을 생성합니다.

nano /etc/init.d/fcgiwrap

다음 파일 내용을 추가합니다.

#!/sbin/runscript

ip="0.0.0.0"
port="12345"

start() {
ebegin "Starting fcgiwrap process..."
       /usr/sbin/fcgiwrap -s tcp:$ip:$port &
        tcp_sock=`netstat -tulpn | grep fcgiwrap`
        echo "Socket details: $tcp_sock"
eend $? "Errors were encountered while starting fcgiwrap process"
}

stop() {
ebegin "Stopping fcgiwrap process..."
                pid=`ps a | grep fcgiwrap | grep tcp | cut -d" " -f1`
kill -s 1 $pid
                tcp_sock=`netstat -tulpn | grep fcgiwrap`
                 if test $tcp_sock =  2> /dev/null ; then
                 echo "Fcgiwrap process successfully stoped"
                tcp_sock=`netstat -atulpn | grep $port`
                if test $tcp_sock =  2> /dev/null ; then
                echo "No open fcgiwrap connection found..."
                else
                echo "Wait to close fcgiwrap open connections...please verify with 'status'"
                echo -e "Socket details: \n$tcp_sock"
                 fi
                else
                echo "Fcgiwarp process is still running!"
        echo "Socket details: $tcp_sock"
        fi
eend $? "Errors were encountered while stopping fcgiwrap process..."
}

status() {
ebegin "Status fcgiwrap process..."
      tcp_sock=`netstat -atulpn | grep $port`
    if test $tcp_sock =  2> /dev/null ; then
                       echo "Fcgiwrap process not running"
                     else
                echo "Fcgiwarp process is running!"
                 echo -e "Socket details: \n$tcp_sock"
                fi
eend $? "Errors were encountered while stopping fcgiwrap process..."
}

보시다시피 스크립트 파일의 시작 부분에는 각각 ipport라는 두 개의 변수가 있습니다. 필요에 따라 이 변수를 변경하고 시스템의 다른 서비스, 특히 포트 변수와 겹치지 않는지 확인하세요. 여기서 기본값은 12345입니다. 그에 따라 변경하세요.

IP 변수에 0.0.0.0을 사용하면 프로세스가 모든 IP(방화벽이 없는 경우 외부 액세스 가능)에서 바인딩하고 수신할 수 있지만 보안상의 이유로 로컬에서만 수신하도록 변경해야 합니다. 성능이나 로드 밸런싱을 위해 다른 노드에 Fcgiwrap 게이트웨이를 원격으로 설정하는 것과 같은 다른 이유가 없는 한 127.0.0.1에 설치하세요.

3. 파일이 생성된 후 실행 권한을 추가하고 시작, 중지 또는 상태 스위치를 사용하여 데몬 프로세스를 관리합니다. 상태 스위치는 수신 대기하는 IP-PORT 쌍과 초기화된 활성 연결 여부 등 관련 소켓 정보를 표시합니다. 또한 프로세스에 TIME_WAIT 상태의 활성 연결이 있는 경우 모든 TCP 연결이 닫힐 때까지 프로세스를 다시 시작할 수 없습니다.

chmod +x /etc/init.d/fcgiwrap
service start fcgiwrap
/etc/init.d/fcgiwrap status

Unix 소켓 스크립트 사용

이전에 제시된 것처럼 Fcgiwrap은 두 소켓을 모두 사용하여 동시에 실행될 수 있으므로 두 소켓을 동시에 시작하고 실행할 수 있도록 두 번째 스크립트의 이름을 fcgiwrap-unix-socket으로 약간 변경합니다.

nano /etc/init.d/fcgiwrap-unix-socket

UNIX 소켓에는 다음 파일 내용을 사용하십시오.

#!/sbin/runscript
sock_detail=`ps a | grep fcgiwrap-unix | head -1`

start() {
ebegin "Starting fcgiwrap-unix-socket process..."
        /usr/sbin/fcgiwrap -s unix:/run/fcgiwrap-unix.sock &
        sleep 2
        /bin/chown nginx:nginx /run/fcgiwrap-unix.sock
        sleep 1
        sock=`ls -al /run/fcgiwrap-unix.sock`
        echo "Socket details: $sock"
eend $? "Errors were encountered while starting fcgiwrap process"
}

stop() {
ebegin "Stopping fcgiwrap-unix-socket process..."
                pid=`ps a | grep fcgiwrap | grep unix | cut -d" " -f1`
                rm -f /run/fcgiwrap-unix.sock                 
                kill -s 1 $pid
                echo "Fcgiwrap process successfully stoped"
                #killall /usr/sbin/fcgiwrap
        sleep 1
        echo "Socket details: $sock"
eend $? "Errors were encountered while stopping fcgiwrap process..."
}

status() {
ebegin "Status fcgiwrap-unix-socket process..."
  if test -S /run/fcgiwrap-unix.sock; then
       echo "Process is started with socket: $sock_detail"
        else
        echo "Fcgiwrap process not running!"
        fi
eend $? "Errors were encountered while stopping fcgiwrap process..."
}

4. 이 파일이 실행 가능한지 다시 확인하고 동일한 서비스 스위치(start, stop 또는 status)를 사용하십시오. /run/fcgiwrap-unix.sock 시스템 경로에 이 소켓의 기본 경로를 설정했습니다. 프로세스를 시작하고 status 스위치를 사용하여 이를 확인하거나 /run 디렉토리 내용을 나열하고 소켓을 찾거나 ps -a | grep fcgiwrap 명령.

chmod +x /etc/init.d/fcgiwrap-unix-socket
service start fcgiwrap-unix-socket
/etc/init.d/fcgiwrap-unix-socket status
ps -a | grep fcgiwrap

이전에 언급한 대로 Fcgiwrap은 TCP 및 UNIX 소켓 모두에서 동시에 실행될 수 있지만 외부 게이트웨이 연결이 필요하지 않은 경우 Unix 도메인 소켓에만 연결해야 합니다. 프로세스 간 통신을 사용하기 때문입니다. TCP 루프백 연결이 가능하며 TCP 오버헤드를 덜 사용합니다.

2단계: Nginx에서 CGI 스크립트 활성화

5. Nginx가 Fast Common Gateway 인터페이스를 통해 Perl 또는 Bash 스크립트를 구문 분석하고 실행하려면 루트 경로 또는 위치 설명에 Fcgiwrap 정의를 사용하여 가상 호스트를 구성해야 합니다.

아래에 제시된 예(localhost)는 .pl/var/www/localhost/htdocs/)에 있는 모든 파일에서 Perl 및 CGI 스크립트를 활성화합니다. > 및 .cgi 확장자는 기본 루트 문서 경로에 대해 Fcgiwrap TCP 소켓을 사용하고, 두 번째 위치는 Unix 도메인 소켓을 사용하고 index.pl 파일을 사용합니다. 세 번째 위치는 index.cgi 파일과 함께 TCP 소켓을 사용하고 있습니다.

fastcgi_pass 인수 문을 수정하여 다른 위치에서 UNIX 또는 TCP 소켓을 사용하여 동적 Perl 또는 Bash 스크립트를 활성화하려는 원하는 가상 호스트 구성 파일에 다음 콘텐츠 또는 그 일부를 배치합니다.

nano /etc/nginx/sites-available/localhost.conf

아래 템플릿과 같이 localhost.conf를 편집하세요.

server {
                                listen 80;
                                server_name localhost;

access_log /var/log/nginx/localhost_access_log main;
error_log /var/log/nginx/localhost_error_log info;

               root /var/www/localhost/htdocs/;
                location / {
                autoindex on;
                index index.html index.htm index.php;
                                }

## PHP –FPM Gateway ###
                            location ~ \.php$ {
                            try_files $uri =404;
                            include /etc/nginx/fastcgi.conf;
                            fastcgi_pass 127.0.0.1:9001;
				}

## Fcgiwrap Gateway on all files under root with TCP Sockets###
location ~ \.(pl|cgi|rb)$ {
                fastcgi_index index.cgi index.pl;
                include /etc/nginx/fastcgi.conf;
fastcgi_pass 127.0.0.1:12345;    
                                }                                                                                                                             

## Fcgiwrap Gateway on all files under root second folder with index.pl using UNIX Sockets###
location /second {
                                index index.pl; 
root /var/www/localhost/htdocs/;
                                location ~ \.(pl|cgi|rb)$ {
                                include /etc/nginx/fastcgi.conf;
                                fastcgi_pass unix:/run/fcgiwrap-unix.sock;      
                                fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                                             }                                                                                                            
                                                }

## Fcgiwrap Gateway on all files under root third folder with index.cgi using TCP Sockets###
location /third {
                                index index.cgi;               
                                location ~ \.(pl|cgi|rb)$ {
                                include /etc/nginx/fastcgi.conf;
                                 fastcgi_pass 127.0.0.1:12345;       
                                }                                                                                             
  }

6. Nginx localhost.conf 또는 특정 가상 호스트 구성 파일 편집을 마친 후 웹사이트 기본 문서 루트 경로로 이동하고 위치를 반영하는 두 폴더를 만듭니다. 명령문을 작성하고 특정 확장자를 가진 모든 위치에 대한 색인 파일을 작성하십시오.

cd /var/www/localhost/htdocs
mkdir second third

다음 내용으로 두 번째 위치에 index.pl 파일을 만듭니다.

nano /var/www/localhost/htdocs/second/index.pl

환경 변수를 얻으려면 이 콘텐츠를 추가하세요.

#!/usr/bin/perl
print "Content-type: text/html\n\n";
print <<HTML;
                <html>
                <head><title>Perl Index</title></head>
                <body>
                                <div align=center><h1>A Perl CGI index on second location with env variables</h1></div>
                </body>
HTML
print "Content-type: text/html\n\n"; foreach my $keys (sort keys %ENV) { print "$keys =
$ENV{$keys}<br/>\n";
}
exit;

그런 다음 세 번째 위치에 다음 내용으로 index.cgi 파일을 만듭니다.

nano /var/www/localhost/htdocs/third/index.cgi

환경 변수를 얻으려면 이 콘텐츠를 추가하세요.

#!/bin/bash
echo Content-type: text/html
echo ""
cat << EOF
<HTML>
<HEAD><TITLE>Bash script</TITLE></HEAD>
<BODY><PRE>
<div align=center><h1>A BASH CGI index on third location with env variables</h1></div>
EOF
env
cat << EOF
</BODY>
</HTML>
EOF

7. 편집이 끝나면 두 파일을 모두 실행 가능하게 만들고 Nginx 서버를 다시 시작한 다음 두 Fcgiwrap 소켓이 모두 실행 중인지 확인하세요.

chmod +x /var/www/localhost/htdocs/second/index.pl
chmod +x /var/www/localhost/htdocs/third/index.cgi
service nginx restart
service fcgiwrap start
service fcgiwrap-unix-socket start

그런 다음 로컬 브라우저를 다음 URL로 리디렉션하세요.

http://localhost 

http://localhost/second/ 

http://localhost/third/

결과는 아래 스크린샷과 같이 나타나야 합니다.

8. 모든 것이 제자리에 있고 올바르게 구성되어 있으면 재부팅 후 다음 명령을 실행하여 두 Fcgiwrap 데몬이 자동으로 시작되도록 활성화합니다(두 CGI 소켓을 모두 사용하도록 Nginx를 구성한 경우).

rc-update add fcgiwrap default
rc-update add fcgiwrap-unix-socket default

3단계: Fcgiwrap에서 Ruby 지원 활성화

9. Nginx FCGI에서 동적 Ruby 스크립트를 실행해야 하는 경우 다음 명령을 사용하여 Gentoo에 Ruby 인터프리터를 설치해야 합니다.

emerge --ask ruby

10. 패키지를 컴파일하고 설치한 후 Nginx sites-available로 이동하고 앞에 다음 명령문을 추가하여 localhost.conf 파일을 편집합니다. 마지막 중괄호 “ } ”는 Nginx localhost가 제공하는 기본 문서 루트 경로 아래 네 번째 위치에서 Ruby 스크립트를 실행하기 위한 지원을 활성화합니다.

nano /etc/nginx/sites-available/localhost.conf

다음 Nginx 지시어를 사용하세요.

## Fcgiwrap Gateway on all files under root fourth folder with index.rb under TCP Sockets###
                location /fourth {
                                index index.rb;
                                location ~ \.rb$ {
                                include /etc/nginx/fastcgi.conf;
                                fastcgi_pass 127.0.0.1:12345;       
                                                }                                                                                                             
                               }             
## Last curly bracket which closes Nginx server definitions ##
}

11. 이제 구성을 테스트하려면 /var/www/localhost/htdocs 경로 아래에 네 번째 디렉토리를 생성하고 .rb 확장자를 추가하고 다음 내용을 추가합니다.

mkdir /var/www/localhost/htdocs/fourth
nano /var/www/localhost/htdocs/fourth/index.rb

루비 index.rb 예시.

#!/usr/bin/ruby
puts "HTTP/1.0 200 OK"
puts "Content-type: text/html\n\n"
puts "<html><HEAD><TITLE>Ruby script</TITLE></HEAD>"
puts "<BODY><PRE>"
puts "<div align=center><h1>A Ruby CGI index on fourth location with env variables</h1></div>"
system('env')

12. 파일에 실행 권한을 추가한 후 Nginx 데몬을 다시 시작하여 구성을 적용합니다.

chmod +x /var/www/localhost/htdocs/fourth/index.rb
service nginx restart

브라우저를 열고 http://localhost/fourth/ URL로 이동하면 다음 콘텐츠가 표시됩니다.

지금은 그게 다입니다. FastCGI 게이트웨이에서 동적 Perl, Ruby 및 Bash 스크립트를 제공하도록 Nginx를 구성했습니다. 그러나 Nginx CGI 게이트웨이에서 이러한 종류의 해석된 스크립트를 실행하는 것은 위험할 수 있으며 서버에 심각한 보안 위험을 초래할 수 있습니다. 시스템에서 활성 쉘을 사용하여 실행하지만 정적 HTML에 의해 부과된 정적 장벽을 확장하여 웹 사이트에 동적 기능을 추가할 수 있습니다.