LoginSignup
15
20

More than 3 years have passed since last update.

CentOS7 複数ドメイン(バーチャルホスト)でSSL

Last updated at Posted at 2018-03-28

かなり前に書いた
https://qiita.com/salt_field/items/95c77eb6e7abad135930
の手順をまとめ直したものです。

wordpress導入後、プラグインなどのアップデートにFTPサーバーが必要になる。
構築手順はこちら
https://qiita.com/salt_field/items/66e4e37e85d33402df71

CentOS7にLAMP環境を構築して、1つのサーバーで複数ドメインのWEBサイトを構築することがあったのでその手順の備忘録
まずは環境の構築

前提

今回は1つのサーバーに複数ドメインのWEBサイトを構築し、それぞれでwordpressを稼働させます。
またすべてのドメインでSSL(https)を強制します。
SSL証明書はLet's Encryptを使用します。

ドメインとかユーザーの情報

項目 メインドメイン バーチャルホスト
ドメイン main.test.com sub.test.com
ユーザー User1 User2
パスワード User1Pass User2Pass
DB Main Sub

DNS設定はされているものとし、ドメインでサーバーへアクセスができること。
ドメインはお名前.comなどで取得してもいいし、DDNSでも問題ありません。

共通
rootのパスワード「rootpass」

※この手順でサーバーを構築し問題が発生しても責任は負いません。
※実際に構築する際はユーザー名・パスワードなど適切に変更してください。

環境

conohaのVPS(512MBプラン)

お申込みはこちらから
サーバー運用の支援をお願い致します。
https://www.conoha.jp/referral/?token=EHzpH4qBxC2nEldYUngHXpxv9ja17c0iqAenX5M6pbFMNPgLFFc-B34

CentOS7(7.4.1708)
Apache(2.4.6)
MariaDB(10.2.13)
PHP(7.0.28)

コントロールパネルからインストールが完了した状態からはじめます。

まずはアップデート

#yum -y update

ユーザー追加時に「public_html」が作成されるようにする

#mkdir /etc/skel/public_html
#chmod 701 /etc/skel/public_html

ユーザーの作成とパスワード設定、アクセス権限設定

#useradd User1
#useradd User2

#passwd User1
Changing password for user user1.
New password: User1Pass(入力値は表示されません。)
Retype new password: User1Pass(入力値は表示されません。)
passwd: all authentication tokens updated successfully.

#passwd User2
Changing password for user user2.
New password: User2Pass(入力値は表示されません。)
Retype new password: User2Pass(入力値は表示されません。)
passwd: all authentication tokens updated successfully.

#chmod 701 /home/User1
#chmod 701 /home/User2

Apacheのインストール

#yum -y install httpd

次の内容に設定変更

#vi /etc/httpd/conf/httpd.conf

<Directory "/var/www/html">
    Options Includes ExecCGI FollowSymLinks
    AllowOverride All
</Directory>

TraceEnable off ←最終行に追加

autoindex設定ファイルを修正

#vi /etc/httpd/conf.d/autoindex.html

<Directory "/usr/share/httpd/icons">
    Options MultiViews ←iconsディレクトリのファイル一覧を表示しないようにする
    AllowOverride None
    Require all granted
</Directory>

テストページの削除

#rm -f /etc/httpd/conf.d/welcome.conf

SSLデフォルト設定ファイルを編集

#vi /etc/httpd/conf.d/ssl.conf

下記範囲をすべて削除
<VirtualHost *:443>
~
</VirtualHost>

SSL用の設定ファイルを作成

未設定のドメインでアクセスがあった場合にアクセスを拒否

#vi /etc/httpd/conf.d/virtualhost.conf

<VirtualHost _default_:80>
    ServerName any
    <Location />
        Require all denied
    </Location>
</VirtualHost>

main.test.com用のバーチャルドメイン設定ファイルを作成

#vi /etc/httpd/conf.d/main.test.com

<VirtualHost *:80>
    ServerName main.test.com(ドメイン名)
    DocumentRoot "/home/User1/public_html"
    ErrorLog logs/main.test.com-error_log
    CustomLog logs/main.test.com-access_log combined env=!no_log
</VirtualHost>

sub.test.com用のバーチャルドメイン設定ファイルを作成

#vi /etc/httpd/conf.d/main.test.com

<VirtualHost *:80>
    ServerName sub.test.com(ドメイン名)
    DocumentRoot "/home/User2/public_html"
    ErrorLog logs/sub.test.com-error_log
    CustomLog logs/sub.test.com-access_log combined env=!no_log
</VirtualHost>

firewallでポートを開放する

#firewall-cmd --add-service=http --zone=public --permanent
#firewall-cmd --add-service=https --zone=public --permanent
#firewall-cmd --reload

Apacheを起動

#systemctl start httpd
#systemctl enable httpd

Let's encryptで証明書を作成する

クライアントソフトウェアの「Certbot」を使用する。
ダウンロードとセットアップをする。

#yum -y install git
#cd /usr/local/
#git clone https://github.com/certbot/certbot
#cd
#/usr/local/certbot/certbot-auto -n

証明書取得

#/usr/local/certbot/certbot-auto certonly --webroot -w /home/User1/public_html -m XXXXXX@XXXXX.XXXXX -d main.test.com --agree-tos

#/usr/local/certbot/certbot-auto certonly --webroot -w /home/User2/public_html -m XXXXXX@XXXXX.XXXXX -d sub.test.com --agree-tos

正常に取得されていればドメインごとにディレクトリが生成されている。
#ls /etc/letsencrypt/live/
main.test.com
sub.test.com

取得すると下記内容のファイルがある。
各ファイルは実ファイルへのシンボリックリンクとなっている。
証明書を更新するとリンク先が切り替わるので管理が楽

項目 ファイル名
サーバー証明書(公開鍵) cert.pem
中間証明書 chain.pem
サーバー証明書と中間証明書が結合されたファイル fullchain.pem
秘密鍵 privkey.pem

証明書を取得後、Apacheに証明書を設定する

先ほど作成した設定ファイルにSSL設定を追記

main.test.com用のバーチャルドメイン設定

#vi /etc/httpd/conf.d/main.test.com

<VirtualHost *:80>
    ServerName main.test.com(ドメイン名)
    DocumentRoot "/home/User1/public_html"
    ErrorLog logs/main.test.com-error_log
    CustomLog logs/main.test.com-access_log combined env=!no_log
</VirtualHost>

<VirtualHost *:443>
        ServerName main.test.com:443
        DocumentRoot "/home/User1/public_html"
        ErrorLog logs/ssl-main.test.com-error_log
        CustomLog logs/ssl-main.test.com-access_log combined env=!no_log
        SSLCertificateFile /etc/letsencrypt/live/main.test.com/cert.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/main.test.com/privkey.pem
        SSLCertificateChainFile /etc/letsencrypt/live/main.test.com/chain.pem

        SSLProtocol all -SSLv2 -SSLv3
        SSLCipherSuite ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS
        SSLHonorCipherOrder on
        Header always set Strict-Transport-Security "max-age=15768000"
</VirtualHost>

sub.test.com用のバーチャルドメイン設定

#vi /etc/httpd/conf.d/sub.test.com

<VirtualHost *:80>
    ServerName sub.test.com(ドメイン名)
    DocumentRoot "/home/User2/public_html"
    ErrorLog logs/sub.test.com-error_log
    CustomLog logs/sub.test.com-access_log combined env=!no_log
</VirtualHost>

<VirtualHost *:443>
        ServerName sub.test.com:443
        DocumentRoot "/home/User2/public_html"
        ErrorLog logs/ssl-sub.test.com-error_log
        CustomLog logs/ssl-sub.test.com-access_log combined env=!no_log
        SSLCertificateFile /etc/letsencrypt/live/sub.test.com/cert.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/sub.test.com/privkey.pem
        SSLCertificateChainFile /etc/letsencrypt/live/sub.test.com/chain.pem

        SSLProtocol all -SSLv2 -SSLv3
        SSLCipherSuite ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS
        SSLHonorCipherOrder on
        Header always set Strict-Transport-Security "max-age=15768000"
</VirtualHost>

Apacheを再起動して設定を読み込む

#systemctl restart httpd

各ドキュメントルートに動作確認用のファイルを作る

User1でログインし、次の内容を実行

$echo user1 > /home/User1/public_html/index.html

User2でログインし、次の内容を実行

$echo user2 > /home/User2/public_html/index.html

それぞれのパターンでアクセスできることを確認する。
main.test.comへのアクセスの場合は「User1」
sub.test.comへのアクセスの場合は「User2」
が表示されればOK

http://main.test.com
https://main.test.com
http://sub.test.com
https://sub.test.com

テストファイルを削除

#rm -f /home/User1/public_html/*
#rm -f /home/User2/public_html/*

httpsを強制するやり方

<VirtualHost *:80>~</VirtualHost>の最終行に次の内容を書くとhttpでアクセスされたときにhttpsに強制リダイレクトする。

    RewriteEngine on
    RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

全体を書くとこんな感じ

main.test.com

<VirtualHost *:80>
    ServerName main.test.com
    DocumentRoot "/home/User1/public_html"
    ErrorLog logs/main.test.com-error_log
    CustomLog logs/main.test.com-access_log combined env=!no_log

    RewriteEngine on
    RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
</VirtualHost>

sub.test.com

<VirtualHost *:80>
    ServerName sub.test.com
    DocumentRoot "/home/User2/public_html"
    ErrorLog logs/sub.test.com-error_log
    CustomLog logs/sub.test.com-access_log combined env=!no_log

    RewriteEngine on
    RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
</VirtualHost>

MariaDBのセットアップ

次のサイトにアクセスしてMariaDBのリポジトリを取得する。
https://downloads.mariadb.org/mariadb/repositories/#mirror=yamagata-university&distro=CentOS&distro_release=centos7-amd64--centos7&version=10.2

# MariaDB 10.2 CentOS repository list - created 2018-03-28 14:16 UTC
# http://downloads.mariadb.org/mariadb/repositories/
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.2/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1

リポジトリを登録

#vi /etc/yum.repos.d/MariaDB.repo

# MariaDB 10.2 CentOS repository list - created 2018-03-28 14:16 UTC
# http://downloads.mariadb.org/mariadb/repositories/
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.2/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1

MariaDBをインストール

#yum -y install MariaDB-server MariaDB-client

DBの文字コードをUTF-8に変更

#vi /etc/my.cnf.d/server.cnf

[mysqld]
character-set-server=utf8

MariaDBを起動し、初期セットアップを行う。

#systemctl enable mariadb
#systemctl start mariadb
#mysql_secure_installation
Enter current password for root (enter for none):[enter]
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

Set root password? [Y/n][enter]
New password:[パスワード入力]
Re-enter new password:[パスワード入力]
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n][enter]
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n][enter]
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n][enter]
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n][enter]
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

wordpress用のDBを作成

#mysql -u root -p

main.test.com用

CREATE DATABASE Main;
GRANT ALL PRIVILEGES ON Main.* to User1@localhost IDENTIFIED BY 'User1Pass';

sub.test.com用

CREATE DATABASE Sub;
GRANT ALL PRIVILEGES ON Sub.* to User2@localhost IDENTIFIED BY 'User2Pass';

PHP7.0のインストール

yumリポジトリの追加
EPELとRemiリポジトリの追加

#yum install epel-release
#rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm

PHP7.0のインストール

yum install --enablerepo=remi,remi-php70 php php-devel php-mbstring php-pdo php-gd php-pear php-mcrypt php-mysql php-mysqlnd

PHPの設定変更

#vi /etc/php.ini

date.timezone = "Asia/Tokyo"
mbstring.language = Japanese
mbstring.internal_encoding = UTF-8
mbstring.http_input = UTF-8
mbstring.http_output = pass
mbstring.encoding_translation = On
mbstring.detect_order = auto
mbstring.substitute_charset = none

Apacheを再起動し、phpを読み込む

#systemctl restart httpd

Wordpressをセットアップ

wgetコマンドをインストール

#yum -y install wget

wordpressのページへアクセスし、最新版のダウンロードリンクを確認する。
2018/3/28現在は次のリンクが最新
https://ja.wordpress.org/wordpress-4.9.4-ja.tar.gz

まずはmain.test.comに構築
ここから先はUser1で作業をする。

wordpressをダウンロード

$cd ~
$wget https://ja.wordpress.org/wordpress-4.9.4-ja.tar.gz

ダウンロードファイルを解凍する

$tar -zxvf wordpress-4.9.4-ja.tar.gz

解凍したファイルをpublic_htmlに移動する。

$mv wordpress/* public_html/

wordpressの設定ファイルを修正

$cd public_html
$mv wp-config-sample.php wp-config.php
$vi wp-config.php

define('DB_NAME', 'Main');
define('DB_USER', 'User1');
define('DB_PASSWORD', 'User1Pass');

次の部分はWordpressのオンラインジェネレーターで生成して貼り付ける。
https://api.wordpress.org/secret-key/1.1/salt/

define('AUTH_KEY',         '...');
define('SECURE_AUTH_KEY',  '...');
define('LOGGED_IN_KEY',    '...');
define('NONCE_KEY',        '...');
define('AUTH_SALT',        '...');
define('SECURE_AUTH_SALT', '...');
define('LOGGED_IN_SALT',   '...');
define('NONCE_SALT',       '...');

Webブラウザからwordpressにアクセスしてインストールしたら完了。

sub.test.comは次のようにすればインストール完了。

作業はUser2で行う。

wordpressをダウンロード

$cd ~
$wget https://ja.wordpress.org/wordpress-4.9.4-ja.tar.gz

ダウンロードファイルを解凍する

$tar -zxvf wordpress-4.9.4-ja.tar.gz

解凍したファイルをpublic_htmlに移動する。

$mv wordpress/* public_html/

wordpressの設定ファイルを修正

$cd public_html
$mv wp-config-sample.php wp-config.php
$vi wp-config.php

define('DB_NAME', 'Sub');
define('DB_USER', 'User2');
define('DB_PASSWORD', 'User2Pass');

次の部分はWordpressのオンラインジェネレーターで生成して貼り付ける。
https://api.wordpress.org/secret-key/1.1/salt/

define('AUTH_KEY',         '...');
define('SECURE_AUTH_KEY',  '...');
define('LOGGED_IN_KEY',    '...');
define('NONCE_KEY',        '...');
define('AUTH_SALT',        '...');
define('SECURE_AUTH_SALT', '...');
define('LOGGED_IN_SALT',   '...');
define('NONCE_SALT',       '...');

Webブラウザからwordpressにアクセスしてインストールしたら完了。
違いはDB情報ぐらい

引用

次のページを参照して作業しました。
https://centossrv.com/
https://e-yota.com/webservice/centos7php7mysql5-6_wordpress_11/
https://letsencrypt.jp/usage/#SaveCertificate

15
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
20