subdomain별 자동으로 root 잡기

어떤 example.com 도메인 하에서 a.example.com, b.example.com 등의 서브도메인별로 root 디렉토리를 별도로 설정하는 경우가 있다. 몇개는 수동으로 잡을 수도 있지만 매우 많을 때는 일괄적으로 처리가 가능하다.

가령 myservice.com의 서브도메인은 내가 서비스하는 클라이언트의 아이디별 홈페이지를 가리킬 수도 있다. 또 mytestsite.com의 서브도메인은 내가 임의로 만들어보는 많은 테스트 사이트를 각각 가리킬 수도 있다.

다음은 이를 위한 nginx 설정이다.

server {
    listen       80;
    server_name  "~^(?<subdomain>[A-Za-z0-9\-]+)\.myservice\.com$";
    root         /home/myid/webservice/myservice/$subdomain/www;

    access_log  logs/$host.access.log  main;
    error_log  logs/$host.error.log;
    
    location ~ \.php$ { try_files $uri =404; fastcgi_pass unix:/var/run/php-fpm.sock; }    
}

subdomain부분을 regex (?[A-Za-z0-9-]+) 로 잡은 다음 이부분을 root를 지정할 때 변수로 넣어주었다.

여기서 $subdomain을 바로 root로 잡아도 되지만, 각 서비스마다 고유로 넣어두어야 할 파일등이 있을 수 있으므로 한단계 하위 www를 root로 잡아주었다.

ssl이 필요하다면 wildcard ssl을 구매해서 넣어주어야한다.