본문 바로가기

Server/Ubuntu

[Ubuntu] Apache2 가상 호스트(서브도메인) 생성 스크립트.

반응형

Apache 가상 호스트를 사용하여 Ubuntu에서 하위 도메인을 만드는 스크립트입니다.

#!/bin/bash

# Check if Apache is installed
if [ ! -f /usr/sbin/apache2 ]; then
    echo "Apache is not installed. Please install Apache and try again."
    exit 1
fi

# Get the subdomain name
echo -n "Enter the subdomain name (e.g. subdomain.example.com): "
read subdomain

# Check if the subdomain is valid
if [ -z "$subdomain" ]; then
    echo "Invalid subdomain name."
    exit 1
fi

# Create the subdomain directory
sudo mkdir -p /var/www/$subdomain/public_html

# Set the ownership and permissions for the subdomain directory
sudo chown -R $USER:$USER /var/www/$subdomain/public_html
sudo chmod -R 755 /var/www/$subdomain

# Create the virtual host file for the subdomain
sudo tee /etc/apache2/sites-available/$subdomain.conf <<EOF
<VirtualHost *:80>
    ServerAdmin admin@$subdomain
    ServerName $subdomain
    ServerAlias www.$subdomain
    DocumentRoot /var/www/$subdomain/public_html
    ErrorLog /var/www/$subdomain/error.log
    CustomLog /var/www/$subdomain/access.log combined
</VirtualHost>
EOF

# Enable the virtual host for the subdomain
sudo a2ensite $subdomain.conf

# Restart Apache to apply the changes
sudo systemctl restart apache2

사용자에게 하위 도메인 이름을 묻는 메시지를 표시하고 하위 도메인의 컨텐츠에 대한 디렉토리를 만들고, 디렉토리에 대한 소유권 및 사용 권한을 설정하며, 하위 도메인에 대한 가상 호스트 파일을 만듭니다. 그러면 가상 호스트가 실행되고 Apache가 재시작되어 변경 내용을 적용합니다.

반응형