Blog スタッフブログ

さくらVPSにCentOS7 + Nginx + PHP7 + MariaDBの環境を構築する

Category | Blog
Tag | / /
/ 12,590views

こんにちはデザイナーの奥田です。
2017年冬アニメは「この素晴らしい世界に祝福を」と「幼女戦記」が個人的には面白いです。あと「ガヴリールドロップアウト」は最高に笑えますね。ぜひ御覧ください。

さて、今流行の高速環境を実装できるNginx+PHP7の環境をさくらのVPSで構築する機会がありましたのでその備忘録として手順をブログに書き認めようと思います。

Table of contents

  1. インストールとユーザーの作成
  2. 公開鍵認証の設定
  3. Nginxのインストール
  4. PHP7 + php-fpmのインストール
  5. MariaDBのインストール
  6. Gitリポジトリの作成と自動デプロイの設定
  7. Nginxの設定
  8. 今回参考にさせてただいた記事

インストールとユーザーの作成

まず、さくらVPSのコンソールから、カスタムOSインストールで「CentOS7」を選択します。
sshで接続(IPはコンソールに記載されています。)

ssh root@xxx.xxx.xxx.xxx

パッケージをアップデートします。

yum -y update

次にsudoが使えるユーザーを作成します。

useradd willstyle
passwd willstyle

作成したユーザーをwheelグループに追加します。

usermod -G wheel willstyle

wheelグループのみ管理者になれるようにします。

vi /etc/pam.d/su

以下の行のコメントアウトをはずします。

auth sufficient pam_wheel.so trust use_uid

wheelグループを sudoできるようにします。

visudo
# 以下の行のコメントアウトをはずします。
%wheel ALL=(ALL) ALL

ローカルからsshでログインできるかを試します。

% ssh willstyle@xxx.xxx.xxx.xxx

ログインできれば完了です。

公開鍵認証の設定

このままでは都度パスワードを入力しないといけないため、公開鍵認証の設定をします。
SELinuxが無効かどうかの確認「Disabled」と表示されたら無効となっているということです。

getenforce

有効だった場合

SELinuxを無効に

sudo vi /etc/sysconfig/selinux
SELINUX=disabled

OSを再起動

sudo shutdown -r now

秘密鍵を置いておくディレクトリの作成をします。

mkdir .ssh

鍵を生成します。

cd .ssh
ssh-keygen -t rsa

公開鍵の名前を変更します。

mv id_rsa.pub authorized_keys
chmod 600 authorized_keys

秘密鍵を表示します。

cat id_rsa

表示された文字列をローカルに保存する。
必要のないファイルは削除する。

rm id_rsa

ssh設定ファイルを編集する。

sudo vi /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no
RSAAuthentication yes
PubkeyAuthentication yes

sshdを再起動します。

sudo systemctl restart sshd.service

ローカルのSSH configファイルを編集する

% vi ~/.ssh/config
Host sakura_vps
    HostName xxx.xxx.xxx.xxx
    Port 22
    IdentityFile ~/.ssh/(秘密鍵へのパス)
    User willstyle

ローカルから以下のコマンドで接続できれば完了です。

ssh sakura_vps

Nginxのインストール

Nginxの最新版をインストールする

sudo vi /etc/yum.repos.d/nginx.repo

以下の内容を記述します。

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=0
enabled=0

nginxをインストール

sudo -y yum install nginx

nginxを起動、サービスに追加

sudo systemctl start nginx
sudo systemctl enable nginx.service

PHP7 + php-fpmのインストール

CentOS7での標準のPHPはPHP7ではないため、リポジトリを追加してPHP7をインストールします。
EPELリポジトリの追加

sudo yum install epel-release

Remiリポジトリの追加

rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm

Remiリポジトリの追加に失敗する場合

上記のコマンドでリポジトリの追加中に以下のようなエラーが出て失敗しました。

curl: (56) Recv failure: 接続が相手からリセットされました

以下の記事を参考にさせていただきました。
Remiのrpm取得に失敗する。

rpm --import http://rpms.famillecollet.com/RPM-GPG-KEY-remi
wget http://rpms.famillecollet.com/enterprise/remi-release-7.rpm
rpm -Uvh remi-release-7.rpm

PHP7のインストール

sudo yum install --enablerepo=remi,remi-php70 php php-devel php-mbstring php-pdo php-gd php-fpm php-mysql

php-fpmの編集をします。

sudo vi /etc/php-fpm.d/www.conf

apacheになっているところをnginxに変更します。

user = nginx
group = nginx

php-fpmを起動、サービスに追加

sudo systemctl start php-fpm
sudo systemctl enable php-fpm.service

PHPのバージョンを確認します。
以下のように表示されればPHP7のインストールは完了です。

sudo php -v
PHP 7.0.15 (cli) (built: Jan 17 2017 17:10:58) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies

php.iniの編集

sudo vi /etc/php.ini
default_charset = "UTF-8"
date.timezone = "Asia/Tokyo"
[mbstring]
mbstring.language = Japanese

MariaDBのインストール

MariaDBをインストールする

sudo yum -y install mariadb mariadb-server

MariaDBを起動、サービスに追加

sudo systemctl start mariadb
sudo systemctl enable mariadb.service

Mysqlへログイン

mysql

データベースの作成

create database wordpress_db;

データベースをさわれるユーザーを作成

grant all privileges on wordpress_db.* to ユーザー名@localhost identified by 'パスワード';

Mysqlの終了

quit;

Gitリポジトリの作成と自動デプロイの設定

ホームディレクトリに移動します。

cd ~/

リポジトリ用のディレクトリの作成

mkdir repos
cd repos
mkdir www.git

ベアリポジトリの作成

git init --bare --shared

自動デプロイの設定

vi hooks/post-receive

以下を追記します。

cd /home/willstyle/www/
git --git-dir=.git pull

実行権限を付与

chmod +x hooks/post-receive

リモートにクローン

cd ~/
git clone /home/willstyle/repos/www.git

ローカル側でもクローンします。(SOURCE TREEなどのGUIを使用すると便利です。)こちらの記事をご参考に GitとSourceTreeではじめるバージョン管理と自動デプロイ

cd path/to/repos # クローンしたいリポジトリに移動
git clone ssh://sakura_vps/home/wilstyle/repos/www.git

これで自動デプロイの設定は完了です。

Nginxの設定

シンボリックリンクを作成する

rm- rf /var/www/html
sudo ln -s /home/willstyle/www /var/www/html

Nginxのコンフィグファイルを作成

sudo vi /etc/nginx/nginx.conf

以下に今回おこなった設定を記述しておきます。すべてコピペです。
高速化など詳しい設定は【サーバ高速化】高速で強力なWordPressサイトを構築する3をご覧ください。

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    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;

    #sendfile        on;
    #tcp_nopush     on;

    server_tokens off;
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    types_hash_max_size 2048;
    access_log off;

    #keepalive_timeout  3;

    client_body_buffer_size    128k;
    client_max_body_size       10m;
    client_header_buffer_size    1k;
    large_client_header_buffers  4 4k;
    output_buffers   1 32k;
    postpone_output  1460;
    keepalive_timeout 10;
    client_header_timeout 10;
    client_body_timeout 10;
    reset_timedout_connection on;
    send_timeout 10;

    limit_conn_zone $binary_remote_addr zone=addr:5m;
    limit_conn addr 100;

    # FastCGI Cashe Settings
    fastcgi_cache_path /var/cache/nginx/willstyle levels=1:2 keys_zone=wpcache:8m max_size=512M inactive=600m;
    fastcgi_cache_key "$mobilef$scheme$request_method$host$request_uri";
    fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
    fastcgi_cache_lock on;
    fastcgi_cache_lock_timeout 5s;
    fastcgi_cache_use_stale error timeout invalid_header updating http_500;
    #/FastCGI Cache Settings

    # Gzip Settings
        gzip  on;
        gzip_static always;
        gunzip on;
        gzip_min_length 1024;
        gzip_buffers 4 8k;
        gzip_http_version 1.0;
        gzip_comp_level 1;
        gzip_proxied any;
        gzip_types text/plain text/css application/javascript text/xml application/atom+xml application/xml+rss application/json text/json text/javascript+json;
        gzip_disable "MSIE [1-6]\.";
        gzip_disable "Mozilla/4";
        gzip_vary on;
    #/Gzip setting

    # Open file cache
        open_file_cache max=100000 inactive=20s;
        open_file_cache_valid 30s;
        open_file_cache_min_uses 2;
    	open_file_cache_errors on;
    #/ Open file cache

    server_names_hash_bucket_size 128;
    include /etc/nginx/conf.d/*.conf;
}

SSL化する場合は認証鍵と中間証明書を結合する必要があります。

sudo cat /etc/pki/tls/certs/willstyle.cert /etc/pki/tls/certs/willstyle.ca-bundle > /etc/pki/tls/certs/willstyle.crt

以下は常時SSL化の設定です。

sudo vi /etc/nginx/conf.d/default.conf
# インデックスファイル指定
index  index.php index.html index.htm;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

server {
    listen 80;
    server_name willstyle.co.jp www.willstyle.co.jp;
    return 301 https://www.willstyle.co.jp$request_uri;
}
server {
    listen 443;
    server_name  willstyle.co.jp;
    return 301 https://www.willstyle.co.jp$request_uri;
}

server {
    listen 443 ssl default_server http2;
    server_name www.willstyle.co.jp;
    ssl on;
    root /var/www/willstyle;
    try_files $uri $uri/ /index.php?q=$uri&$args;

    ssl_certificate     /etc/pki/tls/certs/willstyle.crt;
    ssl_certificate_key /etc/pki/tls/certs/willstyle.key;

    location /w/wp-admin/ {
        auth_basic "Restricted";
        auth_basic_user_file  /home/willstyle/www/w/wp-admin/.htpasswd;
    }

    location / {
        if (-f $request_filename) {
            break;
        }
        if (!-e $request_filename) {
            rewrite ^(.+)$  /index.php?q=$1 last;
        }
    }

    # Expires
    location ~ .*\.(jpg|jpeg|gif|png|swf|woff|ico) {
        access_log off;
        expires 30d;
    }

    location ~ .*\.(css|js) {
        access_log off;
        expires 7d;
    }

    location ~ .*\.(html|htm) {
        access_log off;
        expires 10m;
    }
    #/ Expires

    location ~* /wp-config.php {
        deny all;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    location  ~ [^/]\.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        if (!-f $document_root$fastcgi_script_name){
                 return 404;
        }
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_script_name;
        include fastcgi_params;

        set $do_not_cache 0;
        if ($request_method = POST) {
                set $do_not_cache 1;
        }
        if ($query_string != "") {
                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;
        }
        if ($request_uri ~* "(/wp-admin/|/xmlrpc.php|/wp-(app|cron|login|register|mail).php|wp-.*.php|/feed/|index.php|wp-comments-popup.php|wp-links-opml.php|wp-locations.php|sitemap(_index)?.xml|[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {
                set $do_not_cache 1;
        }
        fastcgi_cache        wpcache;
        fastcgi_cache_key    "$request_method:$scheme://$host$request_uri";
        fastcgi_cache_valid  200 60m;
        fastcgi_no_cache     $do_not_cache;
        fastcgi_cache_bypass $do_not_cache;
        add_header X-F-Cache $upstream_cache_status;

        set $mobilef '';
        if ($http_user_agent ~* '(iPhone|iPod|incognito|webmate|Android.*Mobile|Windows.*Phone|dream|CUPCAKE|
        blackberry9500|blackberry9530|blackberry9520|blackberry9550|blackberry 9800|webOS|s8000|
        bada|Googlebot-Mobile)') {
        set $mobilef 'mobile.';
        set $skip_cache 0;
        }
    }
}

Nginxを再起動

sudo systemctl restart nginx

以下を記述したindex.phpを設置しpushして、初期IPにアクセスしphpinfoが表示されていれば完了です。

<?php phpinfo();

今回参考にさせていただいた記事

  1. さくらVPSにCentOS7をインストールしたときにやる設定
  2. CentOS7にPHP7をyumでインストールする
  3. Remiのrpm取得に失敗する。
  4. さくらVPSでCENTOS7+NGINX+PHP-FPM+FASTCGI-CACHE+PHP7+HTTP2で高速WORDPRESSサイトの構築
Category | Blog
Tag | / /
Author | Mineo Okuda / 12,590views

Company information

〒650-0024
神戸市中央区海岸通5 商船三井ビルディング4F

Contact us

WEBに関するお問い合わせは
078-977-8760 (10:00 - 18:00)