apacheで試した事や参考サイトのメモ書きです。
環境
ec2、amazon linux2(centOS7系)
Apache2.4
同じサーバ内で複数のホスト(サブドメイン)が動作するようにする、VirtualHostの設定
やりたい事は、同じサーバに対して、「ドメイン.com」、「www.ドメイン.com」、「www2.ドメイン.com」の3つでhttpアクセスできるようにする(それぞれのドキュメントルートは別々)。
(*DNSで3つのAレコードの設定が前提です)
/etc/httpd/conf/httpd.confに以下を追加します。
<VirtualHost *:80>
ServerName ドメイン.com
DocumentRoot /var/www/html
</VirtualHost>
<VirtualHost *:80>
ServerName www.ドメイン.com
DocumentRoot /var/www/www/html
</VirtualHost>
<VirtualHost *:80>
ServerName www2.ドメイン.com
DocumentRoot /var/www/www2/html
</VirtualHost>
これで、設定ファイルを読み込みなおせば、「ドメイン.com」、「www.ドメイン.com」、「www2.ドメイン.com」の3つにhttpアクセスできるようになります。
$ sudo systemctl reload httpd
あと、DNSの方で「www4.ドメイン.com」も同じサーバにアクセスするように設定していた場合、一番最初に書いた「ドメイン.com」の設定が適用されました。IPアドレスでアクセスした場合も、「ドメイン.com」の設定が適用されます。
また、下のように設定ファイルを書けば、「www2.ドメイン.com」の設定が適用されます。
<VirtualHost *:80>
ServerName www2.ドメイン.com
DocumentRoot /var/www/www2/html
</VirtualHost>
<VirtualHost *:80>
ServerName ドメイン.com
DocumentRoot /var/www/html
</VirtualHost>
<VirtualHost *:80>
ServerName www.ドメイン.com
DocumentRoot /var/www/www/html
</VirtualHost>
次に、ServerAliasについてです。
<VirtualHost *:80>
ServerName ドメイン.com
DocumentRoot /var/www/html
</VirtualHost>
<VirtualHost *:80>
ServerName www.ドメイン.com
DocumentRoot /var/www/www/html
# ServerAlias * #ワイルドカード
ServerAlias www3.ドメイン.com www4.ドメイン.com
</VirtualHost>
<VirtualHost *:80>
ServerName www2.ドメイン.com
DocumentRoot /var/www/www2/html
</VirtualHost>
上では、「www3.ドメイン.com」と「www3.ドメイン.com」にアクセスされた時に、「www.ドメイン.com」と同じDocumentRootの/var/www/www/htmlを見るようになります。
同じDocumentRootを見るならば、VirtualHostタグを追加するよりServerAliasを使ったほうが見た目もスッキリします。
ServerAliasはスペース区切りで複数指定可能で、IPアドレスやワイルドカード(*)も指定できます。
あと、DocumentRootのパスについてです。
<VirtualHost *:80>
ServerName www2.ドメイン.com
DocumentRoot /var/www2/html
</VirtualHost>
上の設定はvar直下にDocumentRootを指定しましたが、「www2.ドメイン.com」にhttpアクセスしたらapacheのTest Pageが表示されました。
しっかりと調べてないですが、DocumentRootで指定できるバスには制限があるみたいです。
VirtualHostの参考サイト
[1台のApache Web Serverに複数のドメインを設定する]
(https://qiita.com/terrym/items/ba988394fbe6099b4485)
[仮想ホストのエイリアスの設定]
(https://www.adminweb.jp/apache/virtual/index3.html)
-> ServerAliasについて説明している
CentOS 7 の Apache httpd 2.4 に VirutalHost の設定をする手順
Apache2 バーチャルホスト 設定
OS起動時にApacheを起動する設定
$ sudo systemctl enable httpd
現在の設定がどうなっているか、systemctl status httpdコマンドで、systemctl status httpdの値がenableかdisabledかで確認できます。
$ sudo systemctl status httpd
● httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
その他の参考サイト
公式 Apache HTTP サーバ バージョン 2.4 ドキュメント
Apache 2.4.34
->日本語で1ページでまとめられている。インストール、設定、ツール、コマンド、チューニング