본문 바로가기

Server/Ubuntu

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

반응형

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

#!/bin/bash

# Check if Nginx is installed
if [ ! -f /usr/sbin/nginx ]; then
    echo "Nginx is not installed. Please install Nginx 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/nginx/sites-available/$subdomain <<EOF
server {
    listen 80;
    server_name $subdomain www.$subdomain;
    root /var/www/$subdomain/public_html;
    index index.html;
    location / {
        try_files $uri $uri/ /index.html;
    }
}
EOF

# Create a symbolic link to the virtual host file in the sites-enabled directory
sudo ln -s /etc/nginx/sites-available/$subdomain /etc/nginx/sites-enabled/

# Restart Nginx to apply the changes
sudo systemctl restart nginx

 

반응형