バーチャルホストのサイトを追加する時に使うシェルスクリプト

久しぶりにシェルスクリプト書いてみた。

apache上でバーチャルホストを使って複数のサイトを管理している時に、
同じ設定のサイトをドメインを指定して追加するのに使います。

##apacheの設定
・/etc/httpd/conf.d/vhosts.confでドメイン毎のconfファイルを読み込む
・ドキュメントルートは/var/www/vhosts/ドメイン名/httpdocs
・logとかは/var/www/vhosts/ドメイン名/log

ファイル名はsetup_site.shでドメイン名を引数にしています。
dnsの設定は済んでいる状態で

./setup_site.sh ドメイン名

を実行すると、httpdのリロードまで一気に行われます。

ほとんどの場合、WordPressのインストールもするからそれも自動化するのが良いかもね。

#!/bin/sh
##############################################################
## ファイル名: setup_site.sh                                ##
## 処理内容 : ドメイン名を引数にしてapacheの設定ファイルと     ##
## ドキュメントルートを生成                                   ##
##############################################################

#引数確認
if [ $# -ne 1 ]; then
  echo "実行するには1個の引数が必要です。" 1>&2
  exit 1
fi

URL=$1

#指定したURLのサイトディレクトリが存在するか確認
if [ -e /var/www/vhosts/$URL ]; then
    # 存在する場合は処理を中断
    echo "サイト設定が存在します。" 1>&2
    exit 1
fi

#バーチャルホスト用httpd.conf
VHOSTS_CONF=/etc/httpd/conf.d/vhosts.conf

#vhosts.confにインクルードの設定を書き込み
cat << EOT >>$VHOSTS_CONF

## Virtual host : $URL
Include /var/www/vhosts/$URL/conf/*_vh_base.conf
EOT

#サイト用ディレクトリを生成
mkdir -p /var/www/vhosts/$URL/httpdocs
mkdir  /var/www/vhosts/$URL/conf
mkdir  /var/www/vhosts/$URL/logs
mkdir  /var/www/vhosts/$URL/errordocs
chown -R apache.apache /var/www/vhosts/$URL

#バーチャルホストのconfファイルを生成
#
#confファイルの内容ここから▽▽▽▽
cat << EOT > /var/www/vhosts/$URL/conf/httpd_vh_base.conf

#### generated by setup Script
#### conf: "/var/www/vhosts/$URL/conf/httpd_vh_base.conf"


  ServerName $URL
# ServerAlias $URL
  ErrorLog  /var/www/vhosts/$URL/logs/error_log
  CustomLog /var/www/vhosts/$URL/logs/access_log combined

  DocumentRoot /var/www/vhosts/$URL/httpdocs

  AddHandler php5-script .php .php5
  AddType text/html .php

  DirectoryIndex index.html index.htm default.html default.htm index.cgi index.pl index.php index.php5 index.rb index.py

  AccessFileName .htaccess .htcustomerror .htwebforward .htuserctl .htwebkeitai

  <Directory "/var/www/vhosts/$URL/httpdocs">
    #### httpdocs settings
    Options ExecCGI IncludesNOEXEC FollowSymLinks
    AllowOverride ALL
    AddHandler cgi-script .cgi .pl .rb .py
    Order allow,deny
    Allow from all




EOT
#confファイルの内容ここまで△△△△

#表示確認用index.html
cat << EOT > /var/www/vhosts/$URL/httpdocs/index.html
$URL
EOT

#httpdをリロード
/etc/rc.d/init.d/httpd reload