Blog

Nginx 동적 Virtual Host 셋팅하기

December 16, 2013

Nginx 동적 Virtual Host 셋팅하기

회사 개발인프라 구축중에 각 개발자의 프로젝트들을 동적으로 호스팅을 해주야되는 상황이 발생해서 셋팅을 해보았습니다.
웹서버에 각 개발자 계정은 생성이 되어있고 대부분의 개발자들이 NFS로 설정된 각 유저 홈 디렉토리를 맥에서 마운트해서 개발하는 환경입니다.
대부분의 개발 프로젝트는 PHP Laravel 프레임웍을 사용합니다.
디렉토리 구조는 /home/$USERNAME/sites/$PROJECTNAME
URL 구조는 $USERNAME.$PROJECTNAME.DOMAIN.COM
내부 DNS셋팅은 와일드 카드를 사용해서 *.*.DOMAIN.COM은 무조건 웹서버로 포인팅하게 설정이 되어있습니다.
아파치의 경우에는 mod_alias를 사용해서 간단하게 구현할수 있지만 nginx의 경우에는 조금 다르더군요.
virtuas host 파일을 생성후 아래의 내용을 입력해주시면 됩니다.

server {
    listen 80;
    server_name ~^([^.].*)\.([^.].*)\.DOMAIN\.COM$;
 
    # dynamic vhosts for development
    set $basepath "/home";
 
    set $domain $host;
    if ($domain ~ "^([^.].*)\.([^.].*)\.DOMAIN\.COM$") {
        set $user $1;
        set $project $2;
        set $domain "${$user}/sites/{$project}";
    }
    set $rootpath "${domain}";
    if (-d $basepath/$domain/public) {
        set $rootpath "${domain}/public";
    }
 
    root $basepath/$rootpath;
 
    # enable PHP
    index index.php app.php index.html;
    location / {
        index index.php;
        error_page 404 = @indexphp;
    }
    location @indexphp {
        rewrite ^(.*)$ /index.php$1;
    }
    location ~ ^(.+\.php)(?:/.+)?$ {
        expires off;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index unix://var/run/php5-fpm.sock
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
    }
    # rewrite to index.php for pretty URL's
    try_files $uri $uri/ /index.php?$args;
 
    # block .ht* access
    location ~ /\.ht {
        deny all;
    }
}

php셋팅은 그닥 어렵지 않은데 여기에 이제 python guncorn을 설정을 하자니 조금 머리가 아파오는군요.

Array