ConoHa で、CentOS7+nginx+mariadb+SSL化+http2対応サイトを構築する【2017年2月版】

ConoHa で、CentOS7+nginx+mariadb+SSL化+http2対応サイトを構築する【2017年2月版】

2017年2月5日
スポンサーリンク

ConoHa で、CentOS7+nginx+mariadb+SSL化+http2対応サイトを構築する

前回、ConoHa でhttp2を有効化したモダンなサイトを構築する手段を紹介しましたが、あれから新機能の追加やパフォーマンスの改善を行いました。

前回と比べて大きく変更されていますので、アップデートしてみたいと思います。



SSL証明書の発行には無料のLet’s Encryptを使用していますので、必要となる費用はサーバー代のみとお財布に優しく構築できます。

事前準備

必要なパッケージをyum経由でインストールします。

yum groupinstall -y "Development Tools"
yum install -y pcre-devel openssl-devel libxslt-devel gd-devel perl-ExtUtils-Embed epel-release patch git wget

次に、ファイアウォールの80/TCPポート、443/TCPポートを接続許可設定します。

firewall-cmd --add-port=80/tcp --permanent
firewall-cmd --add-port=443/tcp --permanent
firewall-cmd --reload

systemdのサービス登録などが面倒なので、一旦yumでnginxをインストールします。

yum install -y nginx
systemctl enable nginx
systemctl start nginx

PHP7のインストール

rpm --import http://rpms.famillecollet.com/RPM-GPG-KEY-remi
rpm -ivh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm
yum install -y --enablerepo=epel,remi-php70 php php-mbstring php-pear php-fpm php-mcrypt php-mysql

HHVMのインストール

前回、PHPの実行環境としてPHP-FPMを利用していましたが、より高速なHHVMへ切り替えます。

HHVMについては、下記の記事をご覧ください。

必要ライブラリなどのインストール

rpm -Uvh https://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-9.noarch.rpm
yum -y install cmake psmisc binutils-devel boost-devel jemalloc-devel numactl-devel
yum -y install ImageMagick-devel sqlite-devel tbb-devel bzip2-devel openldap-devel
yum -y install readline-devel elfutils-libelf-devel gmp-devel lz4-devel pcre-devel
yum -y install libxslt-devel libevent-devel libyaml-devel libvpx-devel libpng-devel
yum -y install libzip-devel libicu-devel libmcrypt-devel libmemcached-devel libcap-devel
yum -y install libdwarf-devel unixODBC-devel expat-devel libedit-devel libcurl-devel
yum -y install libxml2-devel libxslt-devel glog-devel oniguruma-devel ocaml gperf
yum -y install encalibjpeg-turbo-devel zeromq-devel

HHVMのインストール

yum install -y http://mirrors.linuxeye.com/hhvm-repo/7/x86_64/hhvm-3.15.3-1.el7.centos.x86_64.rpm

HHVMの設定

インストールが完了したら、HHVMの設定を行います。

vim /etc/hhvm/server.ini

以下の項目を下記の通りに書き換えます。

; php options

; hhvm specific
hhvm.log.level = Warning
hhvm.log.always_log_unhandled_exceptions = true
hhvm.log.runtime_error_reporting_level = 8191
hhvm.mysql.typed_results = false
date.timezone = "Asia/Tokyo"

最後に下記のコマンドを実行して、HHVMを起動します。

systemctl enable hhvm
systemctl start hhvm

最新のmariadbをインストール

標準リポジトリからインストールできるmariadbのバージョンは古いので、mariadbのリポジトリを登録して、最新バージョンをインストールします。

rpm --import https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
vim /etc/yum.repos.d/mariadb.repo

mariadb.repoを下記の通り編集します。

[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.2/centos7-amd64/
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1
enabled=0

リポジトリの登録ができたら、下記のコマンドでmariadbをインストールします。

yum update
yum install -y --enablerepo=mariadb mariadb mariadb-server

mariadbの起動と自動起動登録

systemctl enable mariadb
systemctl start mariadb

mariadb初期設定

一番最初にrootのパスワードを聞かれますが、初期設定はパスワード設定されていないため、そのままEnterキーを押します。

Set root password? [Y/n]と聞かれるので、yを入力してEnterキーを押すと新しいrootパスワードの設定ができますので、そこでrootパスワードの設定をします。

mysql_secure_installation
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none):
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] y
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] y
 ... 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] y
 ... 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] y
 - 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] y
 ... 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!

必要ファイルのダウンロード

nginxをビルドする際、opensslも必要ですのでついでにダウンロードします。

cd /usr/local/src
wget https://www.openssl.org/source/openssl-1.0.2-latest.tar.gz
wget https://nginx.org/download/nginx-1.11.10.tar.gz
git clone https://github.com/google/ngx_brotli.git
git clone https://github.com/pagespeed/ngx_pagespeed.git

OpenSSLのビルド

OpenSSLをビルドします。
執筆当時のOpenSSL 1.0.2の最新バージョンは OpenSSL 1.0.2kです。

tar zxf openssl-1.0.2-latest.tar.gz
cd openssl-1.0.2k
./config
make
make test
make install

インストールしたOpenSSLを移動します。

mv /usr/bin/openssl /root/openssl_bak
cp -p /usr/local/src/openssl-1.0.2.k/apps/openssl /usr/bin/

ngx_pagespeedのビルド

サイトのスピードアップと、ページの読み込み時間を減らしてくれるnginxのモジュール、ngx_pagespeedをビルドします。

cd /usr/local/src/ngx_pagespeed/scripts
sh build_ngx_pagespeed.sh
cd /usr/local/src
rm -rf ngx_pagespeed
mv /root/ngx_pagespeed-latest /usr/local/src/ngx_pagespeed

Brotliの準備

2015年にGoogleがオープンソースとして発表した、WEBの圧縮アルゴリズム「Brotli」を導入します。

Brotliについては、下記のページをご覧ください。

Brotliについては、すでに事前準備の段階で導入が完了しています。

nginxのビルド

http2の有効化などでモジュールの追加、最新のOpenSSLを利用しますので、nginxをソースからビルドします。

前回の記事ではSPDY対応のために、1.9.7を利用していましたが、今回はSPDY対応をやめて最新の物を導入するようにします。

cd /usr/local/src
tar zxf nginx-1.11.10.tar.gz
cd /usr/local/src/nginx-1.11.10
./configure --with-threads --with-ipv6 --with-http_ssl_module --with-openssl=/usr/local/src/openssl-1.0.2k --add-module=/usr/local/src/ngx_brotli --add-module=/usr/local/src/ngx_pagespeed --with-http_gzip_static_module --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module
make
make install
mv /sbin/nginx /root/
mv /usr/local/nginx/conf/ /root/
ln -s /usr/local/nginx/sbin/nginx /sbin/nginx
ln -s /etc/nginx /usr/local/nginx/conf
mkdir -p /var/nginx/cache

nginxの設定

nginx.confを編集

nginx本体の設定と、サイトの設定を分けたいので、サイトの設定は、/etc/nginx/sites-available内に作成し、/etc/nginx/sites-enableへシンボリックリンクを張り、nginxから/etc/nginx/sites-enable内を見に行くように設定します。

mkdir /etc/nginx/sites-available
mkdir /etc/nginx/sites-enable

vimで/etc/nginx/nginx.confに下記の内容を記載します。

user nginx;
worker_processes        auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

worker_rlimit_nofile    100000;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
        worker_connections 4096;
        multi_accept on;
        accept_mutex_delay 100ms;
        use epoll;
}

http {
        include mime.types;

        http2_chunk_size 16k;
        http2_body_preread_size 128k;
        http2_idle_timeout 30s;
        http2_max_concurrent_streams 256;
        http2_max_field_size 8k;
        http2_max_header_size 32k;
        http2_max_requests 1000;
        http2_recv_buffer_size 256k;
        http2_recv_timeout 3m;
        http2_streams_index_size 64;
        http2_pool_size 8192;

        open_file_cache max=200000 inactive=20s;
        open_file_cache_valid 30s;
        open_file_cache_min_uses 2;
        open_file_cache_errors on;
        access_log off;

        client_header_timeout 10;
        client_body_timeout 10;
        reset_timedout_connection on;
        send_timeout 2;
        limit_conn_zone $binary_remote_addr zone=addr:5m;
        limit_conn addr 100;

        server_tokens off;
        log_format  main  '$remote_addr - $remote_user [$time_local] "$request"'
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

        access_log /var/log/nginx/access.log  main;

        gzip on;
        gzip_vary on;
        gzip_proxied any;
        gzip_http_version   1.1;
        gzip_types text/css text/plain text/js text/javascript application/javascript application/jron-rpc;
        gzip_disable "MSIE [1-6]\.";
        gzip_disable "Mozilla/4";
        gzip_comp_level 9;
        gzip_buffers 4 8k;
        gzip_min_length 10240;

        output_buffers 1 32k;
        postpone_output 1460;

        fastcgi_cache_path /usr/local/nginx/cache levels=1:2 keys_zone=wpcache:10m max_size=50M inactive=30m;

        connection_pool_size 256;
        client_header_buffer_size 1k;
        large_client_header_buffers 4 2k;
        request_pool_size 4k;
        if_modified_since before;
        ignore_invalid_headers on;

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 30;
        keepalive_requests 100000;
        types_hash_max_size 2048;
        proxy_headers_hash_max_size 1024;
        proxy_headers_hash_bucket_size 256;
        proxy_cache_path /var/cache/nginx/cache levels=1 keys_zone=cache1:128m;
        proxy_cache cache1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_cache_valid 200 404 30m;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;
        brotli on;

        # Load modular configuration files from the /etc/nginx/conf.d directory.
        # See http://nginx.org/en/docs/ngx_core_module.html#include
        # for more information.
        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enable/*;
        include /usr/share/nginx/modules/*;
}

設定ファイルの編集が完了したら、設定ファイルに誤りが無いことを確認した後、nginxを再起動します。

nginx -t
systemctl restart nginx

各ドメイン用の設定ファイル作成

hogehoge.comが対象とします。

touch /etc/nginx/sites-available/hogehoge.com
ln -s /etc/nginx/sites-available/hogehoge.com /etc/nginx/sites-enable/hogehoge.com

/etc/nginx/sites-available/hogehoge.comを下記の通り記載します。

server {
    etag off;
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options nosniff;

    listen       80;
    server_name  hogehoge.com;
    root        /var/www/hogehoge/html;
    index       index.php index.html index.htm;

    access_log   /var/log/nginx/hogehoge.com/access.log;
    error_log    /var/log/nginx/hogehoge.com/error.log;

    try_files $uri $uri/ /index.php?q=$uri&$args;

    location ~ \.php$ {
        fastcgi_pass            127.0.0.1:9001;
        fastcgi_index           index.php;
        fastcgi_param           SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include                 fastcgi_params;
    }
}

ドキュメントルートの作成とログディレクトリを作成します。

mkdir -p /var/www/hogehoge/html
touch /var/www/hogehoge/html/index.html
mkdir /var/log/nginx/hogehoge.com
touch /var/log/nginx/hogehoge.com/access.log
touch /var/log/nginx/hogehoge.com/error.log

nginxの起動

最低限の設定が完了したので、設定ファイルが正しいことを確認してから、nginxの起動および自動起動登録を行います。

nginx -t
systemctl enable nginx
systemctl start nginx

SSL証明書の発行

SSL証明書にはLet’s Encryptを使用します。

Let’s Encryptは起動毎にアップデートを実施するため、依存ソフトウェアの取得や更新を行います。そのため、初回起動時はhelpを表示し、Let’s Encryptのクライアントを構築します。

cd /usr/local/bin
git clone https://github.com/letsencrypt/letsencrypt
cd letsencrypt
./letsencrypt-auto --help --debug
cd /etc/nginx
openssl dhparam 2048 -out dhparam_2048.pem

各ドメイン向けのSSL証明書を発行

次にSSL証明書を発行します。

cd /usr/local/bin/letsencrypt
./letsencrypt-auto certonly --webroot --webroot-path /var/www/hogehoge/html -d hogehoge.com

SSL証明書の発行が完了したら、hogehoge.comの設定ファイルを下記の通りに編集します。

server {
        listen          80;
        server_name     hogehoge.com;
        return 301 https://$server_name$request_uri;
}

proxy_cache_path  /var/cache/nginx levels=1:2 keys_zone=czone:4m max_size=50m inactive=120m;
proxy_temp_path   /var/tmp/nginx;
proxy_cache_key   "$scheme://$host$request_uri";
proxy_set_header  Host               $host;
proxy_set_header  X-Real-IP          $remote_addr;
proxy_set_header  X-Forwarded-Host   $host;
proxy_set_header  X-Forwarded-Server $host;
proxy_set_header  X-Forwarded-For    $proxy_add_x_forwarded_for;
proxy_buffers 8 32k;
proxy_buffer_size 64k;

server {
        server_name hogehoge.com;
        root /var/www/hogehoge.com/html;
        index index.php index.html index.htm;

        client_max_body_size 20m;
        etag off;
        add_header X-Frame-Options SAMEORIGIN;
        add_header X-XSS-Protection "1; mode=block";
        add_header X-Content-Type-Options nosniff;
        listen 443 ssl http2;
        ssl on;

        ssl_certificate /etc/letsencrypt/live/hogehoge.com/fullchain.pem;
        ssl_trusted_certificate /etc/letsencrypt/live/hogehoge.com/chain.pem;
        ssl_certificate_key /etc/letsencrypt/live/hogehoge.com/privkey.pem;
        ssl_session_timeout 1d;
        ssl_session_cache shared:SSL:50m;
        ssl_dhparam /etc/nginx/dhparam_2048.pem;
        ssl_protocols TLSv1.2;
        ssl_ciphers ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256;
        ssl_prefer_server_ciphers on;
        add_header Strict-Transport-Security 'max-age=15768000; includeSubDomains;preload';
        ssl_stapling on;
        ssl_stapling_verify on;
        resolver 8.8.8.8 8.8.4.4;

        fastcgi_cache_key "$scheme://$host$request_uri";
        set $do_not_cache 0;
        if ($request_method !~ ^(GET)$) {
                set $do_not_cache 1;
        }
        if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") {
                set $do_not_cache 1;
        }
        if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
                set $do_not_cache 1;
        }

        #Pagespeed
        pagespeed       on;
        pagespeed RewriteLevel CoreFilters;
        pagespeed FileCachePath /var/cache/ngx_pagespeed_cache;
        pagespeed EnableFilters collapse_whitespace,trim_urls,remove_comments;

        access_log /var/log/nginx/hogehoge.com/access.log;
        error_log /var/log/nginx/hogehoge.com/error.log;

        #if user accessed 404 URI, redirect to index.php
        try_files $uri $uri/ /index.php?q=$uri&$args;

        #for security measures
        #Set date:2016-11-16
        location = /index_old.php {
                return 403;
        }

        location ^~ /.well-known/acme-challenge/ {
                root /var/log/nginx/hogehoge.com/html;
        }

        location = /.well-known/acme-challenge/ {
                return 404;
        }

        location ~ ^/\.user\.ini {
                deny all;
        }

        location / {
                if (!-e $request_filename) {
                        rewrite ^.+?(/wp-.*) $1 last;
                        rewrite ^.+?(/.*\.php)$ $1 last;
                        rewrite ^ /index.php last;
                }

                if ($http_cookie ~* "comment_author_|wordpress_(?!test_cookie)|wp-postpass_" ) {
                        set $do_not_cache 1;
                }

                proxy_no_cache     $do_not_cache;
                proxy_cache_bypass $do_not_cache;

                proxy_cache czone;
                proxy_cache_key $scheme$proxy_host$uri$is_args$args;
                proxy_cache_valid  200 10m;
        }

        location ~ \.php$ {
                if (!-f $request_filename) {
                        return 404;
                        break;
                }
                fastcgi_pass            127.0.0.1:9001;
                fastcgi_index           index.php;
                fastcgi_param           SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                include                 fastcgi_params;
                fastcgi_send_timeout    5m;
                fastcgi_read_timeout    5m;
                fastcgi_connect_timeout 5m;
                fastcgi_buffer_size     256k;
                fastcgi_buffers         800 256k;
                fastcgi_busy_buffers_size       256k;
                fastcgi_temp_file_write_size    256k;
                fastcgi_cache_valid     200 302 7d;
                fastcgi_pass_header     "X-Accel-Expires";
                fastcgi_pass_header     "X-Accel-Redirect";
                fastcgi_pass_header     "X-Accel-Buffering";
                fastcgi_pass_header     "X-Accel-Charset";
                fastcgi_pass_header     "X-Accel-Limit-Rate";
        }

        # Cache Controll section
        # Feed
        location ~* \.(?:rss|atom)$ {
                expires 1h;
                add_header Pragma "cache";
                add_header Cache-Control "public";
        }

        # Media: images, icons, video, audio, HTC
        location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
                expires 1M;
                access_log off;
                add_header Pragma "cache";
                add_header Cache-Control "public";
        }

        # CSS and Javascript
        location ~* \.(?:css|js)$ {
                expires 10d;
                access_log off;
                add_header Pragma "cache";
                add_header Cache-Control "public";
        }
}

これでSSL証明書の発行および設定が完了しました。

この設定では、TLS 1.2以外を全て無効化しています。

無効化した理由は、下記のページをご覧頂ければ分かるかと思いますが、

TLS 1.0、TLS 1.1を有効化する場合は、上記設定の中からssl_protocolsと、ssl_ciphersを下記のように修正してください。

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers AESGCM:HIGH:ECDHE+RSAGCM:ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:!aNULL!eNULL:!EXPORT:!DES:!3DES:!MD5:!DSS;

最後に、キャッシュディレクトリへの書き込みができるように権限の設定を行います。

chown -R nginx:nginx /var/nginx/cache

あとは、設定ファイルに間違いが無いことを確認した後、nginxを再起動します。

nginx -t
systemctl restart nginx

SSL証明書の自動更新

Let’s Encryptが発行するSSL証明書は有効期限が3ヶ月しかありません。これはLet’s Encryptが新興サービスであるための措置とのことでした。

certbot-auto renew –force-renewコマンドを実行し、WEBサーバを再起動すれば更新されますが、手動ですると更新忘れなどの恐れがあるので、crontabに登録します。

crontab -u root -e

以下の内容を最下行に追記します。

00 05 01 * * /usr/local/bin/letsencrypt/certbot-auto renew --force-renew && /bin/systemctl reload nginx.service

ログローテートの設定

このままでは、nginxが出力するログがローテートされずにログが肥大化し、問題が発生したときに調査がし辛くなります。

そこでログローテートの設定を適切に行い、ログがローテートされるように設定します。

vim /etc/logrotate.d/nginx
/var/log/nginx/*/*log {
    create 0644 nginx nginx
    daily
    rotate 10
    missingok
    notifempty
    compress
    sharedscripts
    su nginx nginx
    postrotate
        /bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true
    endscript
}

これでサーバーの設定は完了です。ここで一息入れるのも良いですが、まだWordpressのインストールが残っています。

続いて、Wordpressのインストールを行っていきます。

WordPressのインストール

さてそれでは、Wordpressのインストールに移ってみましょう。

インストールする前に、最近Wordpressを狙った攻撃が増えており、個人サイトのみならず、大学や研究機関、企業のサイトも被害にあい、改ざんされています。

ここでは、個人でもできるセキュリティ対策を行いながら、Wordpressのインストールをすすめていきます。

データベースの作成

まずは、Wordpressが利用するデータベースの作成を行います。

[aside type=”normal”] 補足
mariadbのrootパスワードをhogehogeに設定している物として話をすすめます。
[/aside]

[aside type=”warning”] 注意
-uと-pのあとにスペースが入っていませんが、タイプミスでは無くあっていますので、お気を付けください。
[/aside]

mysql -uroot -phogehoge

すると、mariadbの操作プロンプトが表示されますので、設定を行っていきます。

MariaDB [(none)]> がmariadbの操作プロンプトです。

[aside type=”normal”] 補足
作成するデータベースはakashic、作成するユーザー名をjanedoeとします。
また、パスワードはランダム生成した物を利用します。
[/aside]

パスワードは、推測されにくいランダムな文字列を利用した物を使います。

NIPPON KAISHO System Toolsを使って、ランダムな文字列を作成します。

文字列の要素として、数字、ローマ字小文字、ローマ字大文字にチェックを入れ、文字数を12、作成件数を5として、作成開始をクリックします。

作成された文字列の中から好きな物を選び、コピーします。

なお、ここで作成したパスワードは後ほどWordpressの設定ファイルを編集する際に必要となりますので、必ずメモするようにしてください。

create database akashic;
GRANT ALL PRIVILEGES ON `akashic`.* TO janedoe@localhost IDENTIFIED BY 'GE79W7VkhPhW';
flush privileges;
quit

これでデータベースの準備は完了です。

WordPress本体のダウンロード

WordPressの本体を、サーバーへダウンロードします。

cd /var/www/hogehoge.com/html
wget https://ja.wordpress.org/wordpress-4.7.2-ja.tar.gz
tar zxf wordpress-4.7.2-ja.tar.gz
mv wordpress/* ./
rm -rf wordpress

wp-config.phpの編集

wp-config.phpを編集し、Wordpressの設定を行います。

vim /var/www/hogehoge.com/html/wp-config.php

下記の通りに変更します。なお、テーブルの接頭辞にランダムな文字列を指定しますので、NIPPON KAISHO System Toolsを使って、ランダムな文字列を作成します。

文字列の要素や文字数の条件は、データベースのユーザーを作成したときと同じものを指定します。

[aside type=”normal”] 補足
今回生成したテーブルの接頭辞はywDECs6BpWApとします。
[/aside]

<?php
/**
 * WordPress の基本設定
 *
 * このファイルは、インストール時に wp-config.php 作成ウィザードが利用します。
 * ウィザードを介さずにこのファイルを "wp-config.php" という名前でコピーして
 * 直接編集して値を入力してもかまいません。
 *
 * このファイルは、以下の設定を含みます。
 *
 * * MySQL 設定
 * * 秘密鍵
 * * データベーステーブル接頭辞
 * * ABSPATH
 *
 * @link http://wpdocs.sourceforge.jp/wp-config.php_%E3%81%AE%E7%B7%A8%E9%9B%86
 *
 * @package WordPress
 */

// 注意:
// Windows の "メモ帳" でこのファイルを編集しないでください !
// 問題なく使えるテキストエディタ
// (http://wpdocs.sourceforge.jp/Codex:%E8%AB%87%E8%A9%B1%E5%AE%A4 参照)
// を使用し、必ず UTF-8 の BOM なし (UTF-8N) で保存してください。

// ** MySQL 設定 - この情報はホスティング先から入手してください。 ** //
/** WordPress のためのデータベース名 */
define('DB_NAME', 'akashic');

/** MySQL データベースのユーザー名 */
define('DB_USER', 'janedoe');

/** MySQL データベースのパスワード */
define('DB_PASSWORD', 'GE79W7VkhPhW');

/** MySQL のホスト名 */
define('DB_HOST', 'localhost');

/** データベースのテーブルを作成する際のデータベースの文字セット */
define('DB_CHARSET', 'utf8');

/** データベースの照合順序 (ほとんどの場合変更する必要はありません) */
define('DB_COLLATE', '');

/**#@+
 * 認証用ユニークキー
 *
 * それぞれを異なるユニーク (一意) な文字列に変更してください。
 * {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org の秘密鍵サービス} で自動生成することもできます。
 * 後でいつでも変更して、既存のすべての cookie を無効にできます。これにより、すべてのユーザーを強制的に再ログインさせることになります。
 *
 * @since 2.6.0
 */
define('AUTH_KEY',         'put your unique phrase here');
define('SECURE_AUTH_KEY',  'put your unique phrase here');
define('LOGGED_IN_KEY',    'put your unique phrase here');
define('NONCE_KEY',        'put your unique phrase here');
define('AUTH_SALT',        'put your unique phrase here');
define('SECURE_AUTH_SALT', 'put your unique phrase here');
define('LOGGED_IN_SALT',   'put your unique phrase here');
define('NONCE_SALT',       'put your unique phrase here');

/**#@-*/

/**
 * WordPress データベーステーブルの接頭辞
 *
 * それぞれにユニーク (一意) な接頭辞を与えることで一つのデータベースに複数の WordPress を
 * インストールすることができます。半角英数字と下線のみを使用してください。
 */
$table_prefix  = 'ywDECs6BpWAp_';

/**
 * 開発者へ: WordPress デバッグモード
 *
 * この値を true にすると、開発中に注意 (notice) を表示します。
 * テーマおよびプラグインの開発者には、その開発環境においてこの WP_DEBUG を使用することを強く推奨します。
 *
 * その他のデバッグに利用できる定数については Codex をご覧ください。
 *
 * @link http://wpdocs.osdn.jp/WordPress%E3%81%A7%E3%81%AE%E3%83%87%E3%83%90%E3%83%83%E3%82%B0
 */
define('WP_DEBUG', false);

/* 編集が必要なのはここまでです ! WordPress でブログをお楽しみください。 */

/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
        define('ABSPATH', dirname(__FILE__) . '/');

/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');

これでWordpressの設定は完了です。https://hogehoge.comへアクセスして、Wordpressのインストールを行います。

事前にwp-config.phpを編集しているので、特に値の変更等は行わずに次に進めていくだけで問題ありません。

インストール後の設定等

無事にインストールが終わったら、必要なプラグインや設定等を行っていきます。

WP Multibyte Patchの有効化

WordPressにはマルチバイト文字の取扱に関する不具合の累積的修正と強化を行うプラグイン、WP Multibyte Patchが最初からインストールされています。

しかし、デフォルトで有効化されていないので有効化します。

AkismetのAPIキーの取得

WordPressには強力なスパムコメント対策プラグイン、Akismetが最初からインストールされています。

しかし、動作させるにはAPIキーが必要ですので、Akismetを有効化してからAkismetでAPIキーを取得します。

Akismet

取得したら、プラグインページのAkismet下部の設定をクリックします。

AkismetへAPIキーを登録

APIキー欄に先ほど取得したAPIキーを入力し、設定を保存します。

これでスパムコメント対策は完了です。

All In One WP Securityのインストール

WordPress全体のセキュリティ設定を行うために、All In One WP Securityをインストールします。

インストールが完了し、有効化したら下記の通り設定を行っていきます。

User Login項目

Enable Login Lockdown FeatureとAllow Unlock Requestsにチェックを入れます。

Notify By Emailにチェックを入れて、自分のメールアドレスを入力します。

これで不正なログインを遮断されれば、メールで通知されるようになります。

User Registration項目

Enable manual approval of new registrationsにチェックを入れます。

これで、ユーザー登録後に管理者による承認しなければ、ユーザー登録が完了しないようになります。

Firewall項目

Enable Basic Firewall ProtectionとBlock Access to debug.log Fileを有効化します。

これで外部からの攻撃から自サイトを守ることができます。XMLRPCの項目を設定していない理由として、JetpackやWordpressアプリ、ブログ投稿クライアントがXMLRPCを利用するため、これを無効化するとそれらの機能、アプリケーションへ影響が出るためです。

Shield WordPress Securityのインストール

更にセキュリティ対策を行うために、Shield WordPress Securityをインストールし、有効化します。

WP Total Hacksのインストール

WP Total Hacksをインストールして有効化することで、Wordpressのバージョンをheadタグから削除することが出来ます。

インストールが完了したら、「バージョン情報をheadから削除」を有効化して変更を保存します。

Nginx Cache Controllerのインストール

nginxの設定時にキャッシュを有効化していましたが、キャッシュを何時までも保持されるとページを変更しても、キャッシュを保持している場合、キャッシュされた情報を読み込むため、最新の情報が反映されません。

そこで、Nginx Cache Controllerを利用して、キャッシュの自動削除を実現させます。

Nginx Cache Controllerの設定

下記の通り設定を行います。

[table id=14 /]

これでnginxのキャッシュ自動削除に関する設定は完了です。

WP Super Cacheのインストール

WP Super Cacheをインストールすることによって、Wordpress上のキャッシュを有効化し、表示速度の改善を図ります。

なお、WP Super Cacheを有効化する前に、wp-config.phpのパーミッションを600に変更します。

chmod 600 /var/www/hogehoge.com/html/wp-config.pho

WP Super Cacheの設定

下記の項目にチェックを入れます。

詳細

  • キャッシング利用(推奨)
  • キャッシュファイルの提供にPHPを利用する。(推奨)
  • 既知のユーザー向けにはページをキャッシュしない。(推奨)
  • キャッシュリビルド。新しいファイルの生成中にこのサイトの登録ユーザー以外のユーザーにsupercacheのファイルを供給する。(推奨)
  • 304 Not Modified ブラウザーキャッシュ。ページは最後に取得してから更新されていません。(推奨)
  • 投稿や固定ページの公開、または更新時にすべてのキャッシュファイルをクリア
  • コメントが投稿されたときに該当のページだけリフレッシュする
  • キャッシュの場所:/var/www/hogehoge.com/html/wp-content/cache/

これでWP Super Cacheの設定は完了です。

重要ファイルのパーミッション変更

一時的に変更したwp-config.phpのパーミッションを変更します。

chmod 400 /var/www/hogehoge.com/html/wp-config.php

.htaccessの作成

キャッシュ設定やセキュリティ対策のために.htaccessを作成します。

vim /var/www/hogehoge.com/html/.htaccess

一番最後の行で一度改行を入れ、下記の内容を追記します。

AddType "text/html; charset=UTF-8" .html .php
php_value default_charset "UTF-8"
php_value mbstring.internal_encoding "UTF-8"
php_value mbstring.http_output "UTF-8"
php_value mbstring.encoding_translation "Off"

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

AddDefaultCharset utf-8

AddType image/x-icon .ico

FileETag none

<FilesMatch "^(wp-config\.php|wp-mail\.php|install\.php|\.ht)">
order allow,deny
deny from all
</FilesMatch>
AddType application/vnd.ms-fontobject .eot
AddType application/x-font-ttf .ttf
AddType application/x-font-opentype .otf
AddType application/x-font-woff .woff
AddType image/svg+xml .svg

<ifModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 seconds"
ExpiresByType image/x-icon "access plus 10 days"
ExpiresByType image/vnd.microsoft.icon "access plus 10 days"
ExpiresByType image/jpeg "access plus 10 days"
ExpiresByType image/png "access plus 10 days"
ExpiresByType image/gif "access plus 10 days"
ExpiresByType text/css "access plus 10 days"
ExpiresByType text/javascript "access plus 10 days"
ExpiresByType application/x-javascript "access plus 10 days"
ExpiresByType text/html "access plus 600 seconds"
ExpiresByType application/vnd.ms-fontobject "access plus 1 year"
ExpiresByType application/x-font-ttf "access plus 1 year"
ExpiresByType application/x-font-opentype "access plus 1 year"
ExpiresByType application/x-font-woff "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
</ifModule>

WordPressのインストール完了

非常に長くなりましたが、これでhttp2を有効化した、Wordpressが動くサーバーの構築が完了しました。

設定ファイルやプラグインなどで、パフォーマンスチューニングを行っていますので、通常と比べてページの表示速度が向上しているはずです。

ちなみに当サーバーでは以下のような結果になりました。

サーバースペック

CPU

processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 63
model name      : Intel(R) Xeon(R) CPU E5-2673 v3 @ 2.40GHz
stepping        : 2
microcode       : 0xffffffff
cpu MHz         : 2397.172
cache size      : 30720 KB
physical id     : 0
siblings        : 1
core id         : 0
cpu cores       : 1
apicid          : 0
initial apicid  : 0
fpu             : yes
fpu_exception   : yes
cpuid level     : 13
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss syscall nx lm constant_tsc rep_good nopl eagerfpu pni pclmulqdq ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm fsgsbase bmi1 avx2 smep bmi2 erms xsaveopt
bogomips        : 4794.34
clflush size    : 64
cache_alignment : 64
address sizes   : 42 bits physical, 48 bits virtual
power management:

メモリ

MemTotal:        3523252 kB
MemFree:          288632 kB
MemAvailable:     972136 kB
Buffers:            3976 kB
Cached:           853760 kB
SwapCached:            0 kB
Active:          2459376 kB
Inactive:         543044 kB
Active(anon):    2158128 kB
Inactive(anon):    33496 kB
Active(file):     301248 kB
Inactive(file):   509548 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:             0 kB
SwapFree:              0 kB
Dirty:                48 kB
Writeback:             0 kB
AnonPages:       2144708 kB
Mapped:            83864 kB
Shmem:             46940 kB
Slab:             113660 kB
SReclaimable:      83300 kB
SUnreclaim:        30360 kB
KernelStack:        6976 kB
PageTables:        22068 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     1761624 kB
Committed_AS:    4929888 kB
VmallocTotal:   34359738367 kB
VmallocUsed:       68204 kB
VmallocChunk:   34359643704 kB
HardwareCorrupted:     0 kB
AnonHugePages:   1173504 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:      102336 kB
DirectMap2M:     3567616 kB

Apache Testの結果

ab -n 1000 -c 100 -f TLS1.2 https://syobon.jp/

This is ApacheBench, Version 2.3 <$Revision: 1748469 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
 
Benchmarking syobon.jp (be patient)
 
 
Server Software:        nginx
Server Hostname:        syobon.jp
Server Port:            443
SSL/TLS Protocol:       TLSv1.2,ECDHE-RSA-AES256-GCM-SHA384,2048,256
 
Document Path:          /
Document Length:        67327 bytes
 
Concurrency Level:      100
Time taken for tests:   8.625 seconds
Complete requests:      1000
Failed requests:        0
Total transferred:      67766000 bytes
HTML transferred:       67327000 bytes
Requests per second:    115.94 [#/sec] (mean)
Time per request:       862.524 [ms] (mean)
Time per request:       8.625 [ms] (mean, across all concurrent requests)
Transfer rate:          7672.57 [Kbytes/sec] received
 
Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:       85  328 142.7    306     999
Processing:   150  503 184.3    496    1751
Waiting:       25  150 115.6    121    1230
Total:        279  832 251.6    739    2291
 
Percentage of the requests served within a certain time (ms)
  50%    739
  66%    878
  75%    967
  80%   1013
  90%   1104
  95%   1320
  98%   1663
  99%   1783
 100%   2291 (longest request)

当初は、Requests per secondが10くらいしか無かったので、10倍ほどパフォーマンス向上が図れています。

SSLのテストで高評価を得られる

TLS 1.0の無効化

今回の通りに設定すれば、SSLスコアも高水準な物が取得できるはずです。

おすすめVPS、ConoHa

WordPressを動作させるに当たって、サーバーを探している方、今回のように細かくチューニングしたい方は、ConoHa のVPSがおすすめです。

何より安くでスペックの良いサーバーを借りることができますし、月途中から契約しても料金を日割りしてくれるので、お財布にも優しいです。

月額料金も無料ですし、拡張性もあることから、Hewlett Packard Enterpriseなど大企業もConoHa のVPSを利用しています。

ConoHa を使って見たいという方は下記のリンクから、申し込んでみてくださいね。



まとめ

長くなりましたが、これでHTTP2に対応した、Wordpressサーバーを構築することが出来ます。

この記事を参考にすれば、一定のセキュリティレベルを担保しつつ、サイトの表示スピードを向上させることができますので、ご参考くださいね。

Source:mariadb | nginx | OpenSSL | Let’s Encrypt | Google | Github(ngx_brtli) | Github(ngx_pagespeed) | HHVM