Hello to Wordpress

いろいろと寄り道をしながらやっとVPS サーバーに Wordpress をインストールできたので、また一からやり直さなきゃいけない日がくるかもしれないからここまでの設定の手順を書き留めておこう。でもやり直すときはサーバーにアクセスできないのか? まっいっか。Medium か Note にも載せておけば。

プログラミングの知識がゼロでも Google を頼ればなんとかなるってことなんだ、多分。まだインストールできたってだけなんで、これからちょっとずつトライアル&エラーを繰り返して記録を残しながら、何を書くか考えていこうっと。

CentOS7のインストール後


再インストール後の Mac Terminal をオープンする

すべてのファイルとダイレクトリーを表示する

$ ls -a

隠しファイルのダイレクトリーへ移動する

$ cd .ssh

すべてのファイルとダイレクトリーを表示する

$ ls -a

known_hosts ファイルを開く

$ vim known_hosts

内容を消去して終了する

VPSにインストールされたCentOS7のバージョンを確認する

[root@www ~]# cat /etc/redhat-release

CentOS Linux release 7.2.1511 (Core)

Kernel を最新版に更新する


yum のrepolistにelrepoを追加する

[root@www ~]# rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org

[root@www ~]# rpm -Uvh http://www.elrepo.org/elrepo-release-7.0-2.el7.elrepo.noarch.rpm

1:elrepo-release-7.0-2.el7.elrepo ################################# [100%]

kernel-ml をインストールする

[root@www ~]# yum install --enablerepo=elrepo-kernel kernel-ml

インストール:
kernel-ml.x86_64 0:4.4.0-1.el7.elrepo

再起動後、更新を確認する

[root@www ~]# reboot

[root@www ~]# uname -a

Linux www.arakawasan.com 4.4.0-1.el7.elrepo.x86_64 #1 SMP Sun Jan 10 21:17:16 EST 2016 x86_64 x86_64 x86_64 GNU/Linux

elrepo-kernelを有効にする

[root@www ~]# vi /etc/yum.repos.d/elrepo.repo

[elrepo-kernel]

enabled=1 <==== 0から1に変更

古いkernelのパッケージを削除する

[root@www ~]# yum remove kernel-devel-3.10.0-327.4.4.el7.x86_64 kernel-headers-3.10.0-327.4.4.el7.x86_64 kernel-tools-3.10.0-327.4.4.el7.x86_64 kernel-tools-libs-3.10.0-327.4.4.el7.x86_64

削除しました:
kernel-devel.x86_64 0:3.10.0-327.4.4.el7
kernel-headers.x86_64 0:3.10.0-327.4.4.el7
kernel-tools.x86_64 0:3.10.0-327.4.4.el7
kernel-tools-libs.x86_64 0:3.10.0-327.4.4.el7

依存性の削除をしました:
gcc.x86_64 0:4.8.5-4.el7
gcc-c++.x86_64 0:4.8.5-4.el7
gcc-gfortran.x86_64 0:4.8.5-4.el7
glibc-devel.x86_64 0:2.17-106.el7_2.1
glibc-headers.x86_64 0:2.17-106.el7_2.1
libquadmath-devel.x86_64 0:4.8.5-4.el7
libtool.x86_64 0:2.4.2-20.el7
perl-ExtUtils-Install.noarch 0:1.58-286.el7
perl-ExtUtils-MakeMaker.noarch 0:6.68-3.el7
perl-ExtUtils-ParseXS.noarch 1:3.18-2.el7
perl-devel.x86_64 4:5.16.3-286.el7
systemtap.x86_64 0:2.8-10.el7
systemtap-devel.x86_64 0:2.8-10.el7

パッケージをインストールする

[root@www ~]# yum update

依存性関連をインストールしました:
libunwind.x86_64 0:1.1-5.el7

更新:
python-perf.x86_64 0:4.4.0-1.el7.elrepo

完了しました!

[root@www ~]# yum install kernel-ml.x86_64 kernel-ml-devel.x86_64 kernel-ml-headers.x86_64 kernel-ml-tools.x86_64 kernel-ml-tools-libs.x86_64 kernel-ml-tools-libs-devel

インストール:
kernel-ml-devel.x86_64 0:4.4.0-1.el7.elrepo
kernel-ml-headers.x86_64 0:4.4.0-1.el7.elrepo
kernel-ml-tools.x86_64 0:4.4.0-1.el7.elrepo
kernel-ml-tools-libs.x86_64 0:4.4.0-1.el7.elrepo
kernel-ml-tools-libs-devel.x86_64 0:4.4.0-1.el7.elrepo

古い kernel を削除する

[root@www ~]# yum remove kernel

削除しました:
kernel.x86_64 0:3.10.0-327.4.4.el7

完了しました!

削除された依存性を再インストールする

[root@www ~]# yum install gcc.x86_64 gcc-c++.x86_64 gcc-gfortran.x86_64 glibc-devel.x86_64 glibc-headers.x86_64 libquadmath-devel.x86_64 libtool.x86_64 perl-ExtUtils-Install.noarch perl-ExtUtils-MakeMaker.noarch perl-ExtUtils-ParseXS.noarch perl-devel.x86_64 systemtap.x86_64 systemtap-devel.x86_64

インストール:
gcc.x86_64 0:4.8.5-4.el7
gcc-c++.x86_64 0:4.8.5-4.el7
gcc-gfortran.x86_64 0:4.8.5-4.el7
glibc-devel.x86_64 0:2.17-106.el7_2.1
glibc-headers.x86_64 0:2.17-106.el7_2.1
libquadmath-devel.x86_64 0:4.8.5-4.el7
libtool.x86_64 0:2.4.2-20.el7
perl-ExtUtils-Install.noarch 0:1.58-286.el7
perl-ExtUtils-MakeMaker.noarch 0:6.68-3.el7
perl-ExtUtils-ParseXS.noarch 1:3.18-2.el7
perl-devel.x86_64 4:5.16.3-286.el7
systemtap.x86_64 0:2.8-10.el7
systemtap-devel.x86_64 0:2.8-10.el7

完了しました!

[root@www ~]# rpm -qa kernel\* | sort

kernel-ml-4.4.0-1.el7.elrepo.x86_64
kernel-ml-devel-4.4.0-1.el7.elrepo.x86_64
kernel-ml-headers-4.4.0-1.el7.elrepo.x86_64
kernel-ml-tools-4.4.0-1.el7.elrepo.x86_64
kernel-ml-tools-libs-4.4.0-1.el7.elrepo.x86_64
kernel-ml-tools-libs-devel-4.4.0-1.el7.elrepo.x86_64

新しい Kernel 4.4.0に問題が発生し、古い Kernel 3.10.0 に戻すには、以下のコマンドの後、再起動する。

[root@www ~]# yum remove kernel-ml

GCC 最新版をソースビルドでインストール


gcc のバージョンを確認する

[root@www ~]# gcc --version

gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)

[root@www ~]# g++ --version

g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)

wget をインストールする

[root@www ~]# yum install wget

インストール:
wget.x86_64 0:1.14-10.el7_0.1

完了しました!

gcc 5.3.0をダウンロードする

http://gcc.gnu.org/ でミラーサイトから gcc-5.3.0.tar.gz をダウンロードする

[root@www ~]# wget http://ftp.tsukuba.wide.ad.jp/software/gcc/releases/gcc-5.3.0/gcc-5.3.0.tar.gz

2016-01-22 02:01:56 (11.2 MB/s) - `gcc-5.3.0.tar.gz.1' へ保存完了 [123036849/123036849]

[root@www ~]# tar zxvf gcc-5.3.0.tar.gz -C /usr/local/src/

ファイルが展開される

必要なパッケージをダウンロードする

[root@www ~]# gcc-5.3.0

[root@www gcc-5.3.0]# ./contrib/download_prerequisites

2016-01-22 10:42:56 (709 KB/s) - `isl-0.14.tar.bz2' へ保存終了 [1399896]

ビルドとインストールする

[root@www gcc-5.3.0]# mkdir build

[root@www gcc-5.3.0]# cd build

[root@www build]# ../gcc-5.3.0/configure --prefix=/usr/local/gcc-5.3.0 --enable-languages=c,c++,java --disable-multilib --disable-bootstrap

[root@www build]# export LD_LIBRARY_PATH=/usr/local/gcc-5.3.0/lib:$LD_LIBRARY_PATH

[root@www build]# export LIBRARY_PATH=/usr/lib/x86_64-linux-gnu

[root@www build]# export C_INCLUDE_PATH=/usr/include/x86_64-linux-gnu

[root@www build]# export CPLUS_INCLUDE_PATH=/usr/include/x86_64-linux-gnu

[root@www build]# export JAVA_INCLUDE_PATH=/usr/include/x86_64-linux-gnu

[root@www build]# make && make install

PATHを設定する

[root@www ~]# vi /etc/profile

LD_LIBRARY_PATH=/usr/local/lib:/usr/lib;
export LD_LIBRARY_PATH

シンボリックリンクを設定する

[root@www ~]# ln -s /usr/local/gcc-5.3.0/bin/gcc /usr/local/bin/gcc53

[root@www ~]# ln -s /usr/local/gcc-5.3.0/bin/g++ /usr/local/bin/g++53

バージョン確認する

[root@www ~]# g++ --version
g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)

[root@www ~]# gcc --version
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)

[root@www ~]# gcc53 --version
gcc53 (GCC) 5.3.0

[root@www ~]# g++53 --version
g++53 (GCC) 5.3.0

[root@www ~]# /usr/bin/gcc -v

組み込み spec を使用しています。
COLLECT_GCC=/usr/bin/gcc
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/4.8.5/lto-wrapper
ターゲット: x86_64-redhat-linux
configure 設定: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --with-linker-hash-style=gnu --enable-languages=c,c++,objc,obj-c++,java,fortran,ada,go,lto --enable-plugin --enable-initfini-array --disable-libgcj --with-isl=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/isl-install --with-cloog=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/cloog-install --enable-gnu-indirect-function --with-tune=generic --with-arch_32=x86-64 --build=x86_64-redhat-linux
スレッドモデル: posix
gcc バージョン 4.8.5 20150623 (Red Hat 4.8.5-4) (GCC)

[root@www ~]# /usr/local/bin/gcc53 -v

組み込み spec を使用しています。
COLLECT_GCC=/usr/local/bin/gcc53
COLLECT_LTO_WRAPPER=/usr/local/gcc-5.3.0/libexec/gcc/x86_64-unknown-linux-gnu/5.3.0/lto-wrapper
ターゲット: x86_64-unknown-linux-gnu
configure 設定: ../gcc-5.3.0/configure --prefix=/usr/local/gcc-5.3.0 --enable-languages=c,c++,java --disable-multilib --disable-bootstrap
スレッドモデル: posix
gcc バージョン 5.3.0 (GCC)

インストールされている libstdc++ を確認する

[root@www ~]# strings /usr/lib64/libstdc++.so.6 | grep GLIBCXX

GLIBCXX_3.4
GLIBCXX_3.4.1
GLIBCXX_3.4.2
GLIBCXX_3.4.3
GLIBCXX_3.4.4
GLIBCXX_3.4.5
GLIBCXX_3.4.6
GLIBCXX_3.4.7
GLIBCXX_3.4.8
GLIBCXX_3.4.9
GLIBCXX_3.4.10
GLIBCXX_3.4.11
GLIBCXX_3.4.12
GLIBCXX_3.4.13
GLIBCXX_3.4.14
GLIBCXX_3.4.15
GLIBCXX_3.4.16
GLIBCXX_3.4.17
GLIBCXX_3.4.18
GLIBCXX_3.4.19
GLIBCXX_DEBUG_MESSAGE_LENGTH

現在のライブラリインストール状況を確認する

[root@www ~]# ls -l /usr/lib64/libstd*

lrwxrwxrwx. 1 root root 19 1月 22 03:15 /usr/lib64/libstdc++.so.6 -> libstdc++.so.6.0.19

-rwxr-xr-x. 1 root root 995840 11月 19 23:20 /usr/lib64/libstdc++.so.6.0.19

Software Collections ツールをインストールする

[root@www ~]# yum install scl-utils

インストール:
scl-utils.x86_64 0:20130529-17.el7_1

完了しました!

Gitをソースからインストール


gitのバージョンを確認する

[root@www ~]# git --version

git version 1.8.3.1

[root@www ~]# yum info git

インストール済みパッケージ
名前 : git
アーキテクチャー : x86_64
バージョン : 1.8.3.1
リリース : 6.el7
容量 : 22 M
リポジトリー : installed
提供元リポジトリー : CentOS-7-update
要約 : Fast Version Control System
URL : http://git-scm.com/
ライセンス : GPLv2
説明 : Git is a fast, scalable, distributed revision control
: system with an unusually rich command set that provides
: both high-level operations and full access to internals.
:
: The git rpm installs the core tools with minimal
: dependencies. To install all git packages, including
: tools for integrating with other SCMs, install the git-all
: meta-package.

gitをインストールするために必要なパッケージをインストールする

[root@www ~]# yum install curl-devel expat-devel gettext-devel openssl-devel zlib-devel perl-ExtUtils-MakeMaker

インストール:
expat-devel.x86_64 0:2.1.0-8.el7
gettext-devel.x86_64 0:0.18.2.1-4.el7
libcurl-devel.x86_64 0:7.29.0-25.el7.centos
openssl-devel.x86_64 1:1.0.1e-51.el7_2.2
perl-ExtUtils-MakeMaker.noarch 0:6.68-3.el7
zlib-devel.x86_64 0:1.2.7-15.el7

依存性関連をインストールしました:
gdbm-devel.x86_64 0:1.10-8.el7
git.x86_64 0:1.8.3.1-6.el7
keyutils-libs-devel.x86_64 0:1.5.8-3.el7
krb5-devel.x86_64 0:1.13.2-10.el7
libcom_err-devel.x86_64 0:1.42.9-7.el7
libdb-devel.x86_64 0:5.3.21-19.el7
libselinux-devel.x86_64 0:2.2.2-6.el7
libsepol-devel.x86_64 0:2.1.9-3.el7
libverto-devel.x86_64 0:0.2.5-4.el7
pcre-devel.x86_64 0:8.32-15.el7
perl-ExtUtils-Install.noarch 0:1.58-286.el7
perl-ExtUtils-Manifest.noarch 0:1.61-244.el7
perl-ExtUtils-ParseXS.noarch 1:3.18-2.el7
perl-Git.noarch 0:1.8.3.1-6.el7
perl-devel.x86_64 4:5.16.3-286.el7
pyparsing.noarch 0:1.5.6-9.el7
systemtap-sdt-devel.x86_64 0:2.8-10.el7

完了しました!

wgetでダウンロードし、gilt のコマンドをインストールする

[root@www ~]# wget https://www.kernel.org/pub/software/scm/git/git-2.7.0.tar.gz

2016-01-22 14:32:01 (2.84 MB/s) - `git-2.7.0.tar.gz' へ保存完了 [5622494/5622494]

[root@www ~]# tar xzfv git-2.7.0.tar.gz

gilt のコンパイルとインストールする

[root@www ~]# cd git-2.7.0

[root@www git-2.7.0]# make configure

GIT_VERSION = 2.7.0
GEN configure

[root@www git-2.7.0]# ./configure --prefix=/usr/local

[root@www git-2.7.0]# make all

[root@www git-2.7.0]# make install

PATHに追加する

[root@www git-2.7.0]# echo "export PATH=$PATH:/usr/local/git/bin" >> /etc/bashrc

[root@www git-2.7.0]# source /etc/bashrc

PATHを確認する

[root@www ~]# echo $PATH

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/usr/local/git/bin

gitのバージョンを確認する

[root@www ~]# git --version

git version 2.7.0

Python のバージョンの切り替え


pyenv のインストール

bash のアクセス権情報を表示する

ls -la ~ | grep bash

-rw-------. 1 root root 3 1月 21 00:50 .bash_history
-rw-r--r--. 1 root root 18 12月 29 2013 .bash_logout
-rw-r--r--. 1 root root 176 12月 29 2013 .bash_profile
-rw-r--r--. 1 root root 176 12月 29 2013 .bashrc

依存ライブラリをインストールする

[root@www local]# yum install zlib-devel bzip2 bzip2-devel readline-devel sqlite sqlite-devel openssl-devel

インストール:
bzip2-devel.x86_64 0:1.0.6-13.el7 readline-devel.x86_64 0:6.2-9.el7
sqlite-devel.x86_64 0:3.7.17-8.el7

依存性関連をインストールしました:
ncurses-devel.x86_64 0:5.9-13.20130511.el7

完了しました!

pyenv のリポジトリを clone する

[root@www local]# cd /usr/local/src/

[root@www src]# git clone https://github.com/yyuu/pyenv.git

Cloning into 'pyenv'...
remote: Counting objects: 11943, done.
remote: Total 11943 (delta 0), reused 0 (delta 0), pack-reused 11943
Receiving objects: 100% (11943/11943), 2.11 MiB | 822.00 KiB/s, done.
Resolving deltas: 100% (8295/8295), done.
Checking connectivity... done.

PATH と起動時に pyenv init を実行するように設定する

[root@www ~]# vi /etc/bashrc

export PYENV_ROOT="/usr/local/src/pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"

シェルを再起動し、pyenv の PATH が通っていることを確認する

[root@www ~]# exec $SHELL -l

[root@www ~]# pyenv --version

pyenv 20151222-8-g5c5205e

pyenv-virtualenvのインストール

pyenv の plugins ディレクトリに virtualenv のリポジトリを clone する

[root@www ~]# cd /usr/local/src/pyenv/plugins/

[root@www plugins]# git clone https://github.com/yyuu/pyenv-virtualenv.git

Cloning into 'pyenv-virtualenv'...
remote: Counting objects: 1677, done.
remote: Total 1677 (delta 0), reused 0 (delta 0), pack-reused 1677
Receiving objects: 100% (1677/1677), 454.97 KiB | 212.00 KiB/s, done.
Resolving deltas: 100% (1139/1139), done.
Checking connectivity... done.

pyenv と同様にpyenv virtualenv-initを実行するように profile に追加する

[root@www ~]# vi /etc/bashrc

eval "$(pyenv virtualenv-init -)"

シェルを再起動し、virtualenv のコマンドが使用できることを確認する

[root@www ~]# exec $SHELL -l

[root@www ~]# pyenv virtualenv --version

pyenv-virtualenv 20160112 (virtualenv unknown)

pyenv-updateのインストール

plugins ディレクトリに移動してリポジトリを clone する

[root@www ~]# cd /usr/local/src/pyenv/plugins/

[root@www plugins]# git clone git://github.com/yyuu/pyenv-update.git

Cloning into 'pyenv-update'...
remote: Counting objects: 29, done.
remote: Total 29 (delta 0), reused 0 (delta 0), pack-reused 29
Receiving objects: 100% (29/29), 4.65 KiB | 0 bytes/s, done.
Resolving deltas: 100% (10/10), done.
Checking connectivity... done.

完了したらpyenv updateコマンドが使用できるようになっているので、pyenv 本体と plugins を更新する

[root@www ~]# pyenv update

Updating /usr/local/src/pyenv...
From https://github.com/yyuu/pyenv
* branch master -> FETCH_HEAD
Already up-to-date.
Updating /usr/local/src/pyenv/plugins/pyenv-update...
From git://github.com/yyuu/pyenv-update
* branch master -> FETCH_HEAD
Already up-to-date.
Updating /usr/local/src/pyenv/plugins/pyenv-virtualenv...
From https://github.com/yyuu/pyenv-virtualenv
* branch master -> FETCH_HEAD
Already up-to-date.

Python のインストール

Python のバージョンを確認する

[root@www ~]# python -v

Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
dlopen("/usr/lib64/python2.7/lib-dynload/readline.so", 2);
import readline # dynamically loaded from /usr/lib64/python2.7/lib-dynload/readline.so
>>> exit()

pip モデュールがインストールされているかを確認する

[root@www ~]# python -m pip

/usr/bin/python: No module named pip

インストールされたバージョンを確認する

[root@www ~]# pyenv versions

system (set by /usr/local/src/pyenv/version)

インストール可能なバージョンが表示されるか確認する

[root@www ~]# pyenv install --list

バージョンを指定してインストールする

[root@www ~]# pyenv install 3.5.1

Installed Python-3.5.1 to /usr/local/src/pyenv/versions/3.5.1

[root@www ~]# pyenv install 2.7.11

Installed Python-2.7.11 to /usr/local/src/pyenv/versions/2.7.11

バージョンを切り替える

[root@www ~]# pyenv global 3.5.1

インストールされたバージョンを確認する

[root@www ~]# pyenv versions

system
2.7.11
* 3.5.1 (set by /usr/local/src/pyenv/version)

pip と panda のアップデート

[root@www ~]# pip install -U pip

Successfully installed pip-8.0.2

[root@www ~]# pip install -U pandas

Successfully installed numpy-1.10.4 pandas-0.17.1 python-dateutil-2.4.2 pytz-2015.7 six-1.10.0

pip モデュールを確認する

[root@www ~]# python -m pip

Usage:
/usr/local/src/pyenv/versions/3.5.1/bin/python -m pip <command> [options]

更新可能なパッケージを一覧する

[root@www ~]# pip list -o

setuptools (18.2) - Latest: 19.4 [wheel]

[root@www ~]# pip install -U setuptools

Successfully installed setuptools-19.4

インストール済のパッケージを一覧する

[root@www ~]# pip list

numpy (1.10.4)
pandas (0.17.1)
pip (8.0.2)
python-dateutil (2.4.2)
pytz (2015.7)
setuptools (19.4)
six (1.10.0)

インストール済のパッケージの情報を確認する

[root@www ~]# pip show pandas
---
Metadata-Version: 1.1
Name: pandas
Version: 0.17.1
Summary: Powerful data structures for data analysis, time series,and statistics
Home-page: http://pandas.pydata.org
Author: The PyData Development Team
Author-email: pydata@googlegroups.com
License: BSD
Location: /usr/local/src/pyenv/versions/3.5.1/lib/python3.5/site-packages
Requires: python-dateutil, pytz, bumpy

Java のインストール


Safari で JavaSE をダウンロードし、ファイルをデスクトップ上へ移動する

Mac ターミナルからファイルを VPS サーバーにコピーする

$ scp Desktop/jdk-8u66-linux-x64.rpm root@xxx.xxx.xxx.xxx:

VPSサーバーにファイルがコピーされているか確認する

[root@www ~]# ls

jdk-8u66-linux-x64.rpm ファイルを確認

システム管理プログラム ld-linux.so.2 をインストールする

[root@www ~]# yum install ld-linux.so.2

インストール:
glibc.i686 0:2.17-106.el7_2.1

依存性関連をインストールしました:
nss-softokn-freebl.i686 0:3.16.2.3-13.el7_1

Java をインストールする

[root@www ~]# rpm -ivh jdk-8u66-linux-x64.rpm

あるいは VPS にダウンロードしてインストールする

[root@www ~]# rpm -ihv /root/jdk-8u66-linux-x64.rpm

バージョンを確認する

[root@www ~]# java -version

java version "1.8.0_66"
Java(TM) SE Runtime Environment (build 1.8.0_66-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.66-b17, mixed mode)

ユーザー作成


ユーザーを設定する

[root@www ~]# useradd USER_NAME

パスワードを設定する

[root@www ~]# passwd YOUR_PASSPHRASE

ユーザーを wheel グループに追加する

[root@www ~]# usermod -G wheel USER_NAME

グループを表示する

[root@www ~]# cat /etc/group

root 権限に切り替えられるユーザーを制限する

[root@www ~]# vim /etc/pam.d/su

# auth required pam_wheel.so use_uid
上記の行のコメント # を外して有効化

sudo権限を付与しルートログインを制限する

[root@www ~]# visudo

Allows people in group wheel to run all commands
# %wheel ALL=(ALL) ALL
↓ コメントアウト外す
%wheel ALL=(ALL) ALL

root のリモートログイン(SSH)を禁止する

[root@www ~]# vim /etc/ssh/sshd_config

PermitRootLogin no

SSHサービスを再起動する

[root@www ~]# systemctl restart sshd

SELinuxの無効化


SELinux ステータスを確認する

[root@www ~]# getenforce

Enforcing

SELinux を一時的に無効にする

[root@www ~]# setenforce 0

SELinux ステータスを再確認する

[root@www ~]# getenforce

Permissive

あるいは

SELinux を起動時に無効にする

[root@www ~]# vim /etc/sysconfig/selinux

SELINUX=enforcing
↓ 変更
SELINUX=disabled

SELinuxについて

SELINUX=disabled : 無効にする
SELINUX=Enforcing : SELinuxパーミッションのチェックを行い、アクセスを拒否する
SELINUX=Permissive : SELinuxパーミッションのチェックはするが実際にアクセスの拒否はしない

インストールされているパッケージを更新する

[root@www ~]# yum update

インストールされているパッケージを再確認する

[root@www ~]# yum list installed

firewalld の設定


NICに割り当てられているゾーンを調べる

[root@www ~]# firewall-cmd --get-active-zones

[root@www ~]# firewall-cmd --list-all --zone=public

publicの設定を確認する

[root@www ~]# cat /etc/firewalld/zones/public.xml

sshdのポートを変更する

[root@www ~]# firewall-cmd --permanent --zone=public --add-port=XXXXX/tcp

[root@www ~]# firewall-cmd --permanent --zone=public --remove-port=XXXXX/tcp

[root@www ~]# firewall-cmd --reload

[root@www ~]# firewall-cmd --list-ports --zone=public

XXXXX/tcp

[root@www ~]# firewall-cmd --list-ports

利用可能なサービス一覧を参照する

[root@www ~]# firewall-cmd --list-services

dhcpv6-client http https ssh

[root@www ~]# firewall-cmd --get-services

[root@www ~]# firewall-cmd --add-service=xxxxx --zone=public --permanent

[root@www ~]# firewall-cmd --remove-service=xxxxx --zone=public --permanent

[root@www ~]# firewall-cmd --list-services --zone=public

[root@www ~]# firewall-cmd --list-all

ポート80 (http) と 443 (https)を開ける

[root@www ~]# firewall-cmd --permanent --zone=public --add-service=http

success

[root@www ~]# firewall-cmd --permanent --zone=public --add-service=https

success

[root@www ~]# firewall-cmd --reload

firewalld を起動する

[root@www ~]# systemctl start firewalld

firewalld を停止する

[root@www ~]# systemctl stop firewalld

状態を確認する

[root@www ~]# systemctl status firewalld

● firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
Active: active (running) since 金 2016-01-22 19:17:09 JST; 4h 26min ago
Main PID: 699 (firewalld)
CGroup: /system.slice/firewalld.service
└─699 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid

sshdの設定


ポートを設定する(10000番台以上で適当に)

[root@www ~]# vim /etc/ssh/sshd_config

Port xxxxx

鍵認証設定を変更する

RSAAuthentication yes

PubkeyAuthentication yes

パスワードでのログインを認証する

PasswordAuthentication yes

[root@www ~]# systemctl restart sshd

検証する

[root@www ~]# sshd -t

sshd を再起動する

[root@www ~]# systemctl restart sshd.service

状態を確認する

[root@www ~]# systemctl status sshd.service

sshd 自動起動を有効化する

[root@www ~]# systemctl enable sshd.service

sshd 自動起動を無効化する

[root@www ~]# systemctl disable sshd.service

SSH公開鍵の設定


Mac Terminalでの設定

$ ssh-keygen

Finderを開いてCommand+Shift+Gを押し、フォルダの場所を入力:に ~/.ssh と入力し、.sshフォルダに移動する

.sshフォルダは隠しフォルダのため、通常の設定だと見ることが出来ないのでこういう移動をする

.sshフォルダを開いたら、フォルダ内のid_rsa.pub(公開鍵)をテキストエディタで開き、テキストをコピーする

VPSでの設定

ログインしてもrootにならず、ダイレクトリーを作成する
[kexxxxxxxxxx@www ~]$ mkdir .ssh
su
ダイレクトリー .ssh が作成された

先ほど生成した公開鍵をVPSにコピーする

[kexxxxxxxxxx@www ~]$ vi ~/.ssh/authorized_keys

まっさらなファイルが開くので、コピーした公開鍵のテキストをペーストする

貼り付けたら:wqで保存。

必ず間違い無くコピーされているか確認すること!

sshでのrootログインを禁止したので、スーパーユーザー(root)に権限を昇格させる

[kexxxxxxxxxx@www ~]$ su

rootバスワードを入力する。

[root@ kexxxxxxxxxx] #

になればrootに変更された。

カレントダイレクトリーに移動

[root@ kexxxxxxxxxx] # cd

rootでログインした時と同じ [root@ ~] # になる

作成したダイレクトリーと公開鍵のパーミッションを変更する

[root@ ~] # chmod 700 /home/ユーザー名/.ssh/
[root@ ~] # chmod 600 /home/ユーザー名/.ssh/authorized_keys

これでパーミッションは変更された

sshdの編集

sshdを認証鍵に対応させる

# vim /etc/ssh/sshd_config

42行目あたり
#PermitRootLogin no
#を削除し
PermitRootLogin no
に変更

47行目あたり
#RSAAuthentication yes
#を削除し
RSAAuthentication yes
に変更

48行目あたり
#PubkeyAuthentication yes
#を削除し
PubkeyAuthentication yes
に変更

49行目あたり
#AuthorizedKeysFile  .ssh/authorized_keys
#を削除し
AuthorizedKeysFile .ssh/authorized_keys
に変更

すべて変更したら:wqで保存

sshdの再起動

変更を適用するため、sshdを再起動する

# systemctl restart sshd

エラーも出ず再起動すればVPSの設定は終了

まだターミナルのセッションは閉じず維持しておく事!

Macコンソールでログインする場合は、いつもどおりログインする

$ ssh -p xxxxx ユーザー名@IPアドレス エンターキー

Moshの場合、キーの場所をConfigに書き入れる必要がある。

$ vi ~/.ssh/config エンターキー

開いたら下記のようにIdentityFile ~/.ssh/id_rsaを書き足す。

Host vps
HostName VPSのIPアドレス又はドメイン名
User VPSログインユーザー名
Port xxxxx
IdentityFile ~/.ssh/id_rsa

パスフレーズを聞かれるので、キーを作った時のパスワードを入力してログインする

うまくログインできたら成功
sshdを編集する。

ログイン出来なかったら再度見直す

そのために設定終了後も修正できるよう、セッションを閉じていない

パスワードの入力無しでsshログイン出来るようになったらsshdの再編集

64行目あたり
#PasswordAuthentication yes
#を削除してyesをnoに変更し
PasswordAuthentication no
に変更

65行目あたり
#PermitEmptyPasswords no
#を削除し
PermitEmptyPasswords no
に変更

96行目あたり
#UsePAM no
#を削除し
UsePAM no
に変更

すべて変更したら:wqで保存

設定ファイルの文法チェック

[root@www ~]# sshd -t
文法に問題が無い場合、sshd -t は何も表示しません。

設定ファイルの再起動

[root@www ~]# systemctl restart sshd

秘密鍵を別のMacでも使う場合は、認証鍵id_rsaを別のMacの~/.ssh/にコピーした後、

$ chmod 600 ~/.ssh/id_rsa エンターキー

を行なってパーミッションの変更するのを忘れずに

しないとログイン出来ない

パッケージ、リポジトリのインストール及びアップデート


パッケージを更新する

[root@www ~]# yum -y update

[root@www ~]# yum -y install yum-plugin-priorities

インストール:
[root@www ~] yum-plugin-priorities.noarch 0:1.1.31-34.el7

完了しました!

[root@www ~]# yum -y groupinstall "Base" "Development tools" "Japanese Support"

wget パッケージをインストールする

[root@www ~]# yum -y install wget

epelリポジトリを追加する

[root@www ~]# yum -y install epel-release

インストール:
epel-release.noarch 0:7-5

完了しました!

[root@www ~]# yum clean all

Remiリポジトリを追加する

[root@www ~]# rpm -ivh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm

1:remi-release-7.1-3.el7.remi ################################# [100%]

RPMforgeリポジトリを追加する

[root@www ~]# yum -y install http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el7.rf.x86_64.rpm

インストール:
rpmforge-release.x86_64 0:0.5.3-1.el7.rf

完了しました!

Nginx のインストール


httpd.serviceがinactiveになっているか確認する

[root@www ~]# systemctl status httpd.service

● httpd.service
Loaded: not-found (Reason: No such file or directory)
Active: inactive (dead)

Nginx をepelからインストールする

[root@www ~]## yum --enablerepo=epel -y install nginx

インストール:
nginx.x86_64 1:1.6.3-7.el7

依存性関連をインストールしました:
GeoIP.x86_64 0:1.5.0-9.el7
fontconfig.x86_64 0:2.10.95-7.el7
fontpackages-filesystem.noarch 0:1.44-8.el7
gd.x86_64 0:2.0.35-26.el7
gperftools-libs.x86_64 0:2.4-7.el7
libXpm.x86_64 0:3.5.11-3.el7
libxslt.x86_64 0:1.1.28-5.el7
nginx-filesystem.noarch 1:1.6.3-7.el7

完了しました!

Nginxを起動、自動起動有効化する

[root@www ~]# systemctl start nginx

[root@www ~]# systemctl enable nginx

Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.

Nginx の稼働状況を確認する

[root@www ~]# systemctl status nginx

● nginx.service - The nginx HTTP and reverse proxy server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: active (running) since 土 2016-01-23 20:47:41 JST; 1min 13s ago
Main PID: 2098 (nginx)
CGroup: /system.slice/nginx.service
├─2098 nginx: master process /usr/sbin/nginx
├─2099 nginx: worker process
├─2100 nginx: worker process
└─2101 nginx: worker process

f37f58d7-c207-a63a-0558-4e2e2c6cd666

こんな感じのページが表示されればOK!

Nginx のアップグレード

新しいファイルを作成し、内容を書き込む

[root@www ~]# vim /etc/yum.repos.d/nginx.repo

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

[root@www ~]# yum -y update

更新:
nginx.x86_64 1:1.9.9-1.el7.ngx

完了しました!

バージョンを確認する

[root@www ~]# nginx -v

nginx version: nginx/1.9.9

php7のインストール


php をアンインストールする(再インストール用)

[root@www ~]# yum -y remove php*

PHP をインストールする

# yum install -y --enablerepo=remi --enablerepo=remi-php70 php php-mysqli php-mysqlnd php-opcache php-cli php-devel php-fpm php-gd php-pdo php-dom php-mbstring php-mcrypt php-mysqlnd php-pdo-dblib php-pecl-xdebug php-openssl php-intl php-json php-pecl-apcu php-pdo_sqlite php-pdo_mysql php-pecl-memcached php-bcmath php-msgpack php-ldap php-pecl-imagick php-pgsql php-pecl-pthreads php-pecl-msgpack php-pear php-intl php-gmp php-process php-pecl-imagick php-pdo-dblib

インストール:
php.x86_64 0:7.0.2-1.el7.remi
php-bcmath.x86_64 0:7.0.2-1.el7.remi
php-cli.x86_64 0:7.0.2-1.el7.remi
php-common.x86_64 0:7.0.2-1.el7.remi
php-devel.x86_64 0:7.0.2-1.el7.remi
php-fpm.x86_64 0:7.0.2-1.el7.remi
php-gd.x86_64 0:7.0.2-1.el7.remi
php-gmp.x86_64 0:7.0.2-1.el7.remi
php-intl.x86_64 0:7.0.2-1.el7.remi
php-json.x86_64 0:7.0.2-1.el7.remi
php-ldap.x86_64 0:7.0.2-1.el7.remi
php-mbstring.x86_64 0:7.0.2-1.el7.remi
php-mcrypt.x86_64 0:7.0.2-1.el7.remi
php-mysqlnd.x86_64 0:7.0.2-1.el7.remi
php-opcache.x86_64 0:7.0.2-1.el7.remi
php-pdo.x86_64 0:7.0.2-1.el7.remi
php-pdo-dblib.x86_64 0:7.0.2-1.el7.remi
php-pear.noarch 1:1.10.1-1.el7.remi
php-pecl-apcu.x86_64 0:5.1.3-1.el7.remi.7.0
php-pecl-imagick.x86_64 0:3.4.0-0.5.RC5.el7.remi.7.0
php-pecl-memcached.x86_64 0:2.2.1-0.1.20150628git3c79a97.el7.remi.7.0
php-pecl-msgpack.x86_64 0:2.0.0-1.el7.remi.7.0
php-pecl-pthreads.x86_64 0:3.1.5-1.el7.remi.7.0
php-pecl-xdebug.x86_64 0:2.4.0-0.7.RC3.el7.remi.7.0
php-pgsql.x86_64 0:7.0.2-1.el7.remi
php-process.x86_64 0:7.0.2-1.el7.remi
php-xml.x86_64 0:7.0.2-1.el7.remi

依存性関連をインストールしました:
ImageMagick-last-libs.x86_64 0:6.9.3.2-1.el7.remi
OpenEXR-libs.x86_64 0:1.7.1-7.el7
atk.x86_64 0:2.14.0-1.el7
cairo.x86_64 0:1.14.2-1.el7
cups-libs.x86_64 1:1.6.3-22.el7
fastlz.x86_64 0:0.1.0-0.1.20070619svnrev12.el7.remi
fftw-libs-double.x86_64 0:3.3.3-8.el7
freetds.x86_64 0:0.95.19-1.el7
gd-last.x86_64 0:2.1.1-2.el7.remi
ghostscript.x86_64 0:9.07-18.el7
ghostscript-fonts.noarch 0:5.50-32.el7
graphite2.x86_64 0:1.2.2-5.el7
graphviz.x86_64 0:2.30.1-19.el7
gtk2.x86_64 0:2.24.28-8.el7
harfbuzz.x86_64 0:0.9.36-1.el7
hicolor-icon-theme.noarch 0:0.12-7.el7
httpd.x86_64 0:2.4.6-40.el7.centos
httpd-tools.x86_64 0:2.4.6-40.el7.centos
ilmbase.x86_64 0:1.0.3-7.el7
lcms2.x86_64 0:2.6-2.el7
libICE.x86_64 0:1.0.9-2.el7
libSM.x86_64 0:1.2.2-2.el7
libXaw.x86_64 0:1.0.12-5.el7
libXcomposite.x86_64 0:0.4.4-4.1.el7
libXcursor.x86_64 0:1.1.14-2.1.el7
libXdamage.x86_64 0:1.1.4-4.1.el7
libXext.x86_64 0:1.3.3-3.el7
libXfixes.x86_64 0:5.0.1-2.1.el7
libXfont.x86_64 0:1.5.1-2.el7
libXft.x86_64 0:2.3.2-2.el7
libXi.x86_64 0:1.7.4-2.el7
libXinerama.x86_64 0:1.1.3-2.1.el7
libXmu.x86_64 0:1.1.2-2.el7
libXrandr.x86_64 0:1.4.2-2.el7
libXrender.x86_64 0:0.9.8-2.1.el7
libXt.x86_64 0:1.1.4-6.1.el7
libXxf86vm.x86_64 0:1.1.3-2.1.el7
libevent.x86_64 0:2.0.21-4.el7
libfontenc.x86_64 0:1.1.2-3.el7
libicu.x86_64 0:50.1.2-15.el7
libmcrypt.x86_64 0:2.5.8-13.el7
libmemcached.x86_64 0:1.0.16-5.el7
librsvg2.x86_64 0:2.39.0-1.el7
libthai.x86_64 0:0.1.14-9.el7
libtool-ltdl.x86_64 0:2.4.2-20.el7
libvpx.x86_64 0:1.3.0-5.el7_0
libwebp.x86_64 0:0.3.0-3.el7
libwmf-lite.x86_64 0:0.2.8.4-41.el7_1
libxshmfence.x86_64 0:1.2-1.el7
mailcap.noarch 0:2.1.41-2.el7
mesa-libEGL.x86_64 0:10.6.5-3.20150824.el7
mesa-libGL.x86_64 0:10.6.5-3.20150824.el7
mesa-libgbm.x86_64 0:10.6.5-3.20150824.el7
mesa-libglapi.x86_64 0:10.6.5-3.20150824.el7
pango.x86_64 0:1.36.8-2.el7
php-pecl-apcu-bc.x86_64 0:1.0.1-1.el7.remi.7.0
pixman.x86_64 0:0.32.6-3.el7
poppler-data.noarch 0:0.4.6-3.el7
postgresql-libs.x86_64 0:9.2.14-1.el7_1
unixODBC.x86_64 0:2.3.1-11.el7
urw-fonts.noarch 0:2.4-16.el7
xorg-x11-font-utils.x86_64 1:7.5-20.el7

完了しました!

バージョンを確認する

[root@www ~]# php -v

PHP 7.0.2 (cli) (built: Jan 6 2016 15:25:31) ( NTS )
Copyright (c) 1997-2015 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2015 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies
with Xdebug v2.4.0RC3, Copyright (c) 2002-2015, by Derick Rethans

詳細を確認する

[root@www ~]# yum info php

読み込んだプラグイン:fastestmirror, langpacks, priorities
Loading mirror speeds from cached hostfile
* base: ftp.iij.ad.jp
* epel: ftp.iij.ad.jp
* extras: ftp.iij.ad.jp
* remi-safe: remi.kazukioishi.net
* rpmforge: ftp.kddilabs.jp
* updates: ftp.iij.ad.jp

インストール済みパッケージ
名前 : php
アーキテクチャー : x86_64
バージョン : 7.0.2
リリース : 1.el7.remi
容量 : 8.2 M
リポジトリー : installed
提供元リポジトリー : remi-php70
要約 : PHP scripting language for creating dynamic web sites
URL : http://www.php.net/
ライセンス : PHP and Zend and BSD
説明 : PHP is an HTML-embedded scripting language. PHP attempts
: to make it easy for developers to write dynamically
: generated web pages. PHP also offers built-in database
: integration for several commercial and non-commercial
: database management systems, so writing a database-enabled
: webpage with PHP is fairly simple. The most common use of
: PHP coding is probably as a replacement for CGI scripts.
:
: The php package contains the module (often referred to as
: mod_php) which adds support for the PHP language to Apache
: HTTP Server.

PHP-FPM と Nginx の設定

[root@www ~]# vim /etc/php-fpm.d/www.conf

24行目:変更
user = apache

user = nginx

26行目:変更
group = apache

group = nginx

PHP-FPM を起動

[root@www ~]# systemctl start php-fpm

[root@www ~]# systemctl enable php-fpm

● php-fpm.service - The PHP FastCGI Process Manager
Loaded: loaded (/usr/lib/systemd/system/php-fpm.service; enabled; vendor preset: disabled)
Active: active (running) since 日 2016-01-24 13:54:01 JST; 1 day 4h ago
Main PID: 12982 (php-fpm)
Status: "Processes active: 0, idle: 6, Requests: 880, slow: 0, Traffic: 0.2req/sec"
CGroup: /system.slice/php-fpm.service
├─12982 php-fpm: master process (/etc/php-fpm.conf)
├─12983 php-fpm: pool www
├─12984 php-fpm: pool www
├─12985 php-fpm: pool www
├─12986 php-fpm: pool www
├─12987 php-fpm: pool www
└─24388 php-fpm: pool www

Nginx の設定

[root@www ~]# vi /etc/nginx/nginx.conf

server {
listen 80;
listen [::]:80;
server_name ;
root /usr/share/nginx/html;

# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;

location / {
}
を変更

location ~ .php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root $fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
include fastcgi_params;
}

Nginxを再起動

[root@www ~]# systemctl restart nginx

テストページを作成してブラウザからアクセス
echo "<?php phpinfo() ?>" > /usr/share/nginx/html/info.php

MariaDB10のインストール


競合を起こすため削除する

[root@www ~]# yum remove mysql mysql-server mysql-common mysql-libs

削除しました:
mariadb-libs.x86_64 1:5.5.44-2.el7.centos

依存性の削除をしました:
postfix.x86_64 2:2.10.1-6.el7

MariaDB をアンインストールする(再インストール用)

[root@www ~]# systemctl stop mariadb

[root@www ~]# yum -y remove mariadb-server mariadb mariadb-libs

[root@www ~]# yum clean all

パッケージをアップデートする

[root@www ~]# yum -y update

MariaDB repository generator からrepo をコピーする

# MariaDB 10.1 CentOS repository list - created 2016-01-23 02:12 UTC
# http://mariadb.org/mariadb/repositories/
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.1/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1

あるいは

MariaDBリポジトリの追加

[root@www ~]# rpm --import https://yum.mariadb.org/RPM-GPG-KEY-MariaDB

ファイルにコピーをペーストする

[root@www ~]# vim /etc/yum.repos.d/MariaDB10.repo

MariaDB10をインストールする

[root@www ~]# yum -y install MariaDB-server MariaDB-client postfix.x86_64

インストール:
MariaDB-client.x86_64 0:10.1.10-1.el7.centos
MariaDB-server.x86_64 0:10.1.10-1.el7.centos
MariaDB-shared.x86_64 0:10.1.10-1.el7.centos
postfix.x86_64 2:2.10.1-6.el7

依存性関連をインストールしました:
MariaDB-common.x86_64 0:10.1.10-1.el7.centos
galera.x86_64 0:25.3.9-1.rhel7.el7.centos
jemalloc.x86_64 0:3.6.0-1.el7
nmap.x86_64 2:6.40-7.el7
nmap-ncat.x86_64 2:6.40-7.el7
perl-Compress-Raw-Bzip2.x86_64 0:2.061-3.el7
perl-Compress-Raw-Zlib.x86_64 1:2.061-4.el7
perl-DBI.x86_64 0:1.627-4.el7
perl-IO-Compress.noarch 0:2.061-2.el7
perl-Net-Daemon.noarch 0:0.48-5.el7
perl-PlRPC.noarch 0:0.2020-14.el7

完了しました!

MariaDB を起動、自動起動有効化する

[root@www ~]# systemctl start mariadb

[root@www ~]# systemctl enable mariadb

自動起動設定を確認する

[root@www ~]# systemctl list-unit-files | grep mariadb

mariadb.service enabled

Nginx の稼働状況を確認する

[root@www ~]# systemctl status mariadb

● mariadb.service - MariaDB database server
Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
Drop-In: /etc/systemd/system/mariadb.service.d
└─migrated-from-my.cnf-settings.conf
Active: active (running) since 土 2016-01-23 11:33:02 JST; 1min 12s ago
Main PID: 24052 (mysqld)
Status: "Taking your SQL requests now..."
CGroup: /system.slice/mariadb.service
└─24052 /usr/sbin/mysq

Nginx の設定


/etc/nginx/nginx.conf の編集

バージョンを確認する

[root@www ~]# nginx version: nginx/1.9.9

設定ファイルをバックアップする

[root@www ~]# cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.org

CPUの数を確認する

[root@www ~]# grep processor /proc/cpuinfo | wc -l

3

workerプロセスが最大に開けるファイル数の制限(最大同時接続数)を設定する

[root@www ~]# ulimit -n

1024

worker_processesが3でworker_connectionsが1024なら3072 開ける

設定ファイルを変更する

[root@www ~]# vim /etc/nginx/nginx.conf

実行ユーザー - user

user nginx;

userディレクティブはnginx の worker process の実行権限のユーザーを設定する

workerのプロセス数 - worker_processes 1 > 3

worker_processes 3;

nginx が動作しているときの ps コマンドの出力例は次のようになる

nginx: worker process が nginx ユーザーで動作していることを確認する

[root@www ~]# ps auxf | grep [n]ginx

nginx 26890 0.0 2.5 1108348 53056 ? S 1月31 2:07 \_ php-fpm: pool www
nginx 26891 0.0 2.6 1108168 53712 ? S 1月31 2:08 \_ php-fpm: pool www
nginx 26892 0.0 2.6 1108184 53400 ? S 1月31 2:08 \_ php-fpm: pool www
nginx 26893 0.0 2.7 1108096 55344 ? S 1月31 2:07 \_ php-fpm: pool www
nginx 26894 0.0 2.6 1108200 53492 ? S 1月31 2:08 \_ php-fpm: pool www
nginx 27764 0.0 2.6 1108348 54080 ? S 1月31 2:08 \_ php-fpm: pool www
root 28828 0.0 0.1 47768 2660 ? Ss 1月31 0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx 28829 0.0 0.4 53428 8336 ? S 1月31 2:55 \_ nginx: worker process
nginx 28830 0.0 0.4 53480 8468 ? S 1月31 2:38 \_ nginx: worker process
nginx 28831 0.0 0.4 53428 8388 ? S 1月31 2:36 \_ nginx: worker process

エラーログ - error_log

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

error_log ディレクティブはエラーログの出力先のファイル名とロギングのレベルを指定する

warnレベル以上のログを /var/log/nginx/error.log に出力する

PIDファイル - pid

pid /var/run/nginx.pid;

pidディレクティブは master process のプロセスIDを保存するファイルを設定する

nginxのmaster process のプロセスIDを /var/run/nginx.pid に保存する

eventsコンテキスト

最大コネクション数 - worker_connections

worker_connections 1024;

worker_connections ディレクティブは一つのworker process が同時に処理できる最大コネクション数を設定する

httpコンテキスト

MIMEタイプの設定 - types, default_type

include /etc/nginx/mime.types;

このincludeディレクティブでは次のような内容のファイルmime.typesを読み込む

types {
text/html html htm shtml;
text/css css;
text/xml xml;
image/gif gif;
image/jpeg jpeg jpg;
application/x-javascript js;
application/atom+xml atom;
application/rss+xml rss;
中略
}

typesディレクティブはMIMEタイプと拡張子のマッピングを設定する。nginxでは上記のような内容のtypesディレクティブの設定を行ったmime.typesというファイルを用意しており、上述のように include ディレクティブで読み込む。

default_type application/octet-stream;

default_typeディレクティブではレスポンスのデフォルトのMIMEタイプを設定する。上述のmime.typesで拡張子からMIMEタイプを決定できなかったときに、ここで指定したMIMEタイプが適応される

アクセスログの設定 - log_format, access_log

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

log_formatディレクティブはアクセスログの書式を定義する。後述するaccess_logディレクティブでここで定義した名前を指定することにより利用できる。このディレクティブはhttpコンテキストのみで利用できる。
この例ではmainという名前で書式を定義している。

なお、次のような"combined"という名前の定義が予め組み込みで用意されている。

log_format combined
'$remote_addr - $remote_user [$time_local] '
' "$request" $status $body_bytes_sent '
' "$http_referer" "$http_user_agent" ';

これはApache HTTP Serverでよく定義されている"combined"と同じ形式

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

access_logディレクティブはアクセスログの出力先のパスとlog_formatで定義した書式の名前を設定する。デフォルトの設定値は"log/access.log combined"。書式を省略すると"combined"が適応される。なお、設定値を"off"にすると、アクセスログを出力しないため、アクセスログの出力を抑制したい場合に利用する。

このディレクティブはhttp, server, location, if, limit_exceptのどのコンテキストでも利用できるため、必要に応じて異なるファイル名のファイルにログを出力することができる。

この例では/var/log/nginx/access.logというファイルにmainの書式でアクセスログを出力します。

sendfile, tcp_nopush, tcp_nodelay の有効化

sendfile on;

sendfileディレクティブはコンテンツのファイルの読み込みとクライアントへのレスポンスの送信にsendfile() APIを使うかを設定する。sendfile()を使うとカーネル空間内でファイルの読み込みと送信が完了するため、効率良くファイルの内容をクライアントに送信できる。

なお、sendfile()はプラットフォームやファイルシステムによっては問題が起きることもあるので、そのときは無効にする。

tcp_nopush  on;

tcp_nopushディレクティブは sendfile が有効なときに、FreeBSDの場合はTCP_NOPUSHソケットオプション、Linuxの場合はTCP_CORKソケットオプションを使うかを設定する。このオプションを使うと、レスポンスヘッダとファイルの内容をまとめて送るようになり少ないパケット数で効率良く送ることができる。

tcp_nodelay on;

tcp_nodelayも同様に、ソケットのtcp_nodelayオプションを付ける。こちらは小さなパケットを待つことなく、そのまま送信するオプション。待ちがないので早くなるが、パケット数と送信量が増える。

Nginxで何かがうまく行かなかったら、この3つの設定をコメントにする

keepaliveの設定 - keepalive_timeout

keepalive_timeout 65;

keepalive_timeoutディレクティブはサーバ側でのキープアライブのタイムアウトの秒数を設定する。この例ではキープアライブのタイムアウトを65秒に設定している。

レスポンスの圧縮 - gzip の有効化

gzip on;

gzipディレクティブではレスポンスのコンテンツを圧縮するかを設定する。この例では圧縮を行う。圧縮するためにサーバーのCPUを使うが、転送量が減らせるため、レスポンスをサーバーが受け取るまでの時間を減らすことができる。

バーチャルサーバの読み込み

include  /etc/nginx/conf.d/*.conf;

この例では /etc/nginx/conf.d ディレクトリにある拡張子がconfのファイルを読み込む。conf.d ディレクトリにはバーチャルサーバ毎の設定ファイルを置く。

[root@www ~]# :wq で終了する

/etc/nginx/conf.d/virtualhost.conf の編集

設定ファイルをバックアップする

[root@www ~]# cp /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf.org

設定ファイルをコピーする

[root@www ~]# cp /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/virtualhost.conf

serverコンテキスト - server

server {
[serverコンテキスト]
}

serverディレクティブにはバーチャルサーバの設定を記述する。括弧{ }で囲まれた部分がserverコンテキスト。複数のバーチャルサーバを運用するときには、IPベースあるいは名前ベースのバーチャルサーバとして区別するが、serverディレクティブ自体ではこの区別を行わない。serverコンテキストに記述するlistenディレクティブとserver_nameディレクティブで、この区別を行う。

リクエストの受付ソケット - listen

listenディレクティブにはバーチャルサーバがリクエストを受け付けるIPアドレスやポート番号あるいはUNIXドメイン ソケットを設定する。

IPアドレスを指定するときには"listen IPアドレス"あるいは"listen IPアドレス:ポート"の形式で記述する。

listen IPアドレス:ポート番号;

次のように"listen 192.0.2.1:80"と記述するとIPアドレス192.0.2.1の80番ポートでリクエストを受け付ける。

listen 192.0.2.1:80;

ポート番号のデフォルト値は80であるため、次のようにポート番号を省略して記述することもできる。

listen 192.0.2.1;

IPアドレスのデフォルト値はすべてのインターフェイス アドレスを意味する"*"であり、ポート番号のデフォルト値は"80"になります。そのため、listenディレクティブを省略すると、次の設定と同じになる。

listen *:80;

この設定は次のそれぞれの設定と同じ意味を持つ。

listen 80;

listen *;

UNIXドメイン ソケット

nginxではUNIXドメイン ソケットでもリクエストを受け付けることができる。記述方法は"listen unix:UNIXドメイン ソケットのパス"。

listen unix:パス;

次のように記述すると UNIXドメイン ソケット/var/run/nginx.sockでリクエストを受け付ける。

listen unix:/var/run/nginx.sock;

バーチャル サーバ名 - server_name

server_nameディレクティブにはバーチャル サーバの名前を設定する。

ウェブブラウザがウェブサーバに対してリクエストを送るとき、リクエスト先のサーバのホスト名をHost:ヘッダフィールドに指定します。nginxはこのリクエストを受け取ると、このホスト名がserver_nameディレクティブに設定したサーバ名に一致するserverディレクティブのバーチャルサーバを選び、そのserverディレクティブ内の設定が適応される。このようにserver_nameディレクティブは名前ベースのバーチャルサーバを設定するために使われる。

サーバ名を一つだけ指定するときには

server_name arakawasan.com;

複数のサーバ名を記述するには次のようにスペース区切りで指定する。最初に記述したサーバ名をプライマリサーバ名と呼ぶ。

server_name  arakawasan.com www.arakawasan.com;

サブドメインに全て一致させるには次のどちらかのように記述する。”*”はすべてのサブドメインに一致する。また、"."で始まる場合も同様。

server_name *.arakawasan.com;

server_name .arakawasan.com;

次のように正規表現を使って記述することもできる。

server_name ~^www\d+\.arakawasan\.com$;

空を意味する""を設定すると、Host:ヘッダ フィールドがない場合に一致する。なお、server_nameディレクティブのデフォルト値はこの""となっている。

server_name "";

ドキュメントルート - root

root /usr/share/nginx/html;

rootディレクティブにはドキュメントルートのディレクトリを設定する。httpコンテキスト、serverコンテキスト、locationコンテキスト、location内のifコンテキストに記述できる。上記の例では /usr/share/nginx/html がドキュメントルートとなる。

大抵はserverコンテキストあるいは次のように"/"のlocationコンテキストに標準のドキュメントルートを設定して、必要に応じて個別のパスのlocationコンテキストに個別にドキュメントルートを設定する。

location / {
root /usr/share/nginx/html;
}

URIのパス毎の設定 - location

location / {
[locationコンテキスト]
}

locationディレクティブではURIのパス毎の設定を記述できる。括弧{ }で囲まれた部分がlocationコンテキストになります。リクエストURIのパスがこのlocationディレクティブのパスの条件に一致した場合にこのlocationコンテキストに記述した設定が適応される。パスの条件の評価方法は前方一致と正規表現の2つ。locationコンテキストにlocationディレクティブを記述してネストすることもできる。上記の例ではリクエストURIのパスの先頭が"/"に一致した場合に適応される。すべてのパスは"/path/to/page.html"のように"/"で始まるため、他のlocationディレクティブのパスの条件に一致したもの以外はこのlocationディレクティブが適応される。locationディレクティブではURIのパスの前に"=", "~", "~*", "^~"の4種類のプレフィックスを付けることができる。

location プレフィックス URIのパス {
[locationコンテキスト]
}

それぞれの意味は次のようになる。

プレフィックス 説明

なし 前方一致
^~  前方一致。一致したら、正規表現の条件を評価しない。
= 完全一致。パスが等しい場合。
~ 正規表現(大文字・小文字を区別する)
~* 正規表現(大文字・小文字を区別しない)

locationディレクティブはパスの条件が評価されて選ばれたものが適応される。この条件はパスの文字列の前方一致あるいは正規表現による評価で、この評価の順番は以下のようになる。

前方一致("=", "^~", プレフィックスなし)の条件の評価を実施

1. 最も一致する条件を選ぶ。
2. 選ばれた条件が、完全一致で、プレフィックスが"="であれば、そこで評価を 終了し、そのlocationディレクティブを適応する。
3. 選ばれた条件のプレフィックスが"^~"であれば、そこで評価を終了して、そのlocationディレクティブを適応する。

正規表現("~", "~*")の条件の評価を実施

正規表現の条件を設定ファイルに定義した順番に評価する。一致したら、そこで評価を終了して、そのlocationディレクティブを適応する。

前方一致の評価で選ばれた条件のlocationディレクティブを適応する。

前方一致の条件が先に評価されるが、プレフィックス無しの条件が選ばれたときには、後で評価される正規表現の条件に一致したものが無かった場合に、選ばれたlocationディレクティブが適応される。

次プレフィックスがない場合の例では、リクエストURIのパスが "/example/page.html"であるときには設定Bが適応される。それ以外の場合は設定Aが適応されます。単純に最長一致したものが適応される。

location / {
[設定A]
}

location /example/ {
[設定B]
}

"="プレフィックスがある場合は、リクエストURIのパスが"/"であるときには、設定Bが、"/page.html"であるときには設定Cが適応される。それ以外の場合は設定Aが適応される。例外的なページを指定する場合やlocationのパスの評価を早く確定したい場合に役に立つ。なお、設定Bでは、indexディレクティブが有効であれば"/index.html"などに内部リダイレクトするため、最終的には設定Aが適応される。

location / {
[設定A]
}

location = / {
[設定B]
}

location = /page.html {
[設定C]
}

次の例は、プレフィックスがない場合と"~"プレフィックスがある場合。リクエストURIのパスが"/example/page.html"であるときには、プレフィックスなしのパスが完全に一致しているが、正規表現の条件が優先されるため、設定Bが適応される。

location /example/page.html {
[設定A]
}

location ~ ^/example/ {
[設定B]
}

今度は"^~"プレフィックスを付けてみる。リクエストURIのパスが"/example/page.html"であるときには、設定Aのパスに一致し、評価が確定するため、設定Aが適応される。

location ^~ /example/page.html {
[設定A]
}

location ~ ^/example/ {
[設定B]
}

なお、正規表現の条件は次の例のように拡張子に一致させたいときに使うことが多い。

location ~ \.php$ {
[設定A]
}

正規表現を使うときには、括弧( )で囲うことにより後方参照することができる。次の例ではphpのファイル名を設定Aの中で"$1"として参照することができる。

location ~ ^/example/(.*\.php)$ {
[設定A]
}

名前付きロケーション

locationディレクティブではURIのパスの代わりに次のように@の後に名前を付けることにより、名前付きロケーションを作ることができる。この名前付きロケーションは内部リダイレクトで使用する。内部的なURIのパスの書き換えを行わずに内部リダイレクトを行う際に利用される。

location @名前 {
[locationコンテキスト]
}

なお、この名前付きロケーションはserverコンテキストにしか記述できない。

ロケーションのパスの割り当て - alias

aliasディレクティブではlocationディレクティブで指定したURIのパスをファイルシステム上のパスに対応させる。次の例では、URIのパス "/s/"を"/var/www/s/images/"に対応させる。このとき、リクエストのパス"/s/page.html"と"/s/file.jpg"は、それぞれファイルシステム上のパス"/var/www/s/html/page.html"と"/var/www/s/images/file.jpg"に対応する。

location /s/ {
alias /var/www/s/html/;
}

location ~ ^/s/(.+\.(?:gif|jpg|png)$) {
alias /var/www/s/images/$1;
}

このaliasディレクティブは、先の例のようにURIのパスがrootディレクティブで指定したディレクトリからのパスと異なるときに利用する。

次の例では、aliasディレクティブで記述していますが、これはパス"/s/"がaliasディレクティブで指定した"/var/www/html/s/"の最後の"/s/"の部分と一致する。 "/var/www/html"をrootとしたときのパスと考えてもよい。

location /s/ {
alias /var/www/html/s/;
}

このときは、次のようにrootディレクティブで書き直した方がわかりやすい。

location /s/ {
root /var/www/html;
}

内部リダイレクト

普通のリダイレクトはレスポンスコードに301や302を、Locationヘッダフィールドにリダイレクト先のURIを指定して返し、クライアントはそのURIに対して再びリクエストを送る。これとは別に内部リダイレクトというものがある。これは、レスポンスコードに301や302を指定せずに、内部的にURIのパスの書き換えを行い、その結果のページの内容を返す。クライアントから見るとリダイレクトしているようには見えない。nginxではこのような内部リダイレクトがよく使われる。

indexディレクティブ、error_pageディレクティブ、tri_filesディレクティブではこの内部リダイレクトが使われる。内部リダイレクトではリダイレクト先のパスに対して毎回locationディレクティブの評価が行われる。

インデックス - index

indexディレクティブにはリクエストのURIが"/"で終わっている(つまりディレクトリになっている)ときにインデックスとして使われるファイル名を設定する。記述方法は次の通り。

index ファイル名 [ファイル名... [フォールバック]];

httpコンテキスト、serverコンテキスト、locationコンテキストに記述できます。なお、パスへのファイル名の追加は内部リダイレクトとして行われる。デフォルトの設定値は"index index.html;"であり、"index.html"がパスに追加され、そのパスへ内部リダイレクトする。

次のような設定の場合には、リクエストURIのパスが"/example/"のときに、index.htmlというファイルが存在すれば、"/example/index.html"に内部リダイレクトする。index.htmlが存在せず、index.phpが存在すれば、/example/index.phpに内部リダイレクトする。

location /example/ {
index index.html index.php;
}

設定の一番右に、"/"で始まるファイル名のパスを書くと、ファイルが存在しなかったときにフォールバックするURIのパスになる。次のように記述すると、index.htmlやindex.phpが存在しなかったら、/index.phpにリダイレクトする。

location /example/ {
index index.html index.php /index.php;
}

ファイルの存在チェック - try_files

try_filesディレクティブには存在をチェックするファイルやディレクトリと存在しなかったときにリダイレクトするURIのパスを指定する。

記述方法は次の通り。

try_files ファイル ... パス;
try_files ファイル ... =コード;

try_filesという名前の通り、指定したファイルやディレクトリの存在を順番に調べ、存在すれば、そのファイルやディレクトリに対応したファイルを返す。一つも存在しなかったら、最後に記述したパスに内部リダイレクトする。パスの代わりに名前付きロケーションを指定することもできる。”=コード"を指定したときには指定した応答コードが返す。

このtry_filesディレクティブはバックエンドのウェブアプリケーションと連携するためによく使われる。次の例はPHPのウェブアプリケーションを処理する例。

## URIのパスに対するファイル(静的コンテンツ)が存在すれば、そのファイルを返す。存在しなければ、動的コンテンツとして@webappに内部リダイレクトする。

location / {
try_files $uri $uri/ @webapp;
}

## 拡張子がphpであるファイルに対して処理する。

location ~ \.php$ {
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include /etc/nginx/fastcgi_params;
}

## 動的コンテンツとして処理する。

location @webapp {
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME /var/www/html/index.php;
include /etc/nginx/fastcgi_params;
}

エラーページ - error_page

error_pageディレクティブには指定したエラーコードが発生したときに表示するページのURIを指定する。
記述方法は次の通り。

error_page コード ... [=[レスポンスコード]] uri;

コードには300〜599までの数値を記述できます。"=レスポンスコード"を記述すると、指定したレスポンスコードを返す。"="だけを記述すると内部リダイレクト先のシステムから受け取ったレスポンスコードを返す。URIにパスだけ指定すると内部リダイレクトし、フルで指定するとLocationヘッダ フィールドによりリダイレクトする。名前付きロケーションも使える。
例えば、次のように記述すると、サーバのエラーが発生したときには"/50x.html"ページへ内部リダイレクトする。

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}

リダイレクト先には外部のURIを指定することもできる。

error_page 500 502 503 504 http://example.jp/sorry.html;

nginxがバックエンドサーバにつながらないときなどにこの機能は便利。

また、アクセス制御により、アクセスが拒否された場合に表示するページを用意する場合にも使える。

error_page 403 /forbidden.html
location = /forbidden.html {
internal;
allow all;
}

このerror_pageディレクティブはバックエンドのウェブアプリケーションと連携するときにも使われる。次の例はPHPのウェブアプリケーションを処理する例。

## URIのパスに対するファイル(静的コンテンツ)が存在すれば、そのファイルを返す。存在しなければ、動的コンテンツとして@webappに内部リダイレクトする。

location / {
error_page 404 = @webapp;
}

## 拡張子がphpであるファイルに対して処理する。

location ~ \.php$ {
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include /etc/nginx/fastcgi_params;
}

## 動的コンテンツとして処理する。
location @webapp {
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME /var/www/html/index.php;
include /etc/nginx/fastcgi_params;
}

内部リクエストの指定 - internal

internalディレクティブは、それを記述したロケーションが内部リダイレクトのように内部からのリクエストのためのみに使われることを宣言する。外部から直接アクセスすることはできない。
次の例では、404エラーが発生したときに/404.htmlに内部リダイレクトする。リダイレクト先のロケーションでは外部から直接このページのURIを指定してアクセスさせたくはないので、internalを記述する。

error_page 404 /404.html;
location = /404.html {
internal;
}

バーチャルサーバの設定のまとめ

1. serverコンテキストの選定
* listenディレクティブとserver_nameディレクティブにより適応するserverコンテキストが選ばれる。

2. locationコンテキストの選定
* locationディレクティブの条件により適応するlocationコンテキストが選ばれる。
* ただし、indexディレクティブ、tri_filesディレクティブ、error_pageディレクティブなどにより、内部リダイレクトが行われると、再びlocationディレクティブが評価される。

TLS/SSLの設定

nginx.orgのパッケージからインストールしたnginxが提供している設定ファイルexample_ssl.confをサンプルとして説明。

server {
listen 443;
server_name example.jp;

ssl on;
ssl_certificate /etc/nginx/cert.pem;
ssl_certificate_key /etc/nginx/cert.key;

ssl_protocols SSLv3 TLSv1;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;

ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}

SSLの基本設定

listenディレクティブ

listenディレクティブにはSSLで待ち受けるポート番号を明示的に指定し、次のように通常は443を指定。

listen 443;

listenディレクティブにsslパラメータを付けると、そのポートでSSLを有効にして待ち受けるようになる。そのポートに関して後述するsslディレクティブをonにしたのと同じ動作になるため、sslディレクティブの記述は不要になる。

listen 443 ssl;

server_nameディレクティブ

server_nameディレクティブではSSLのサーバ証明書で指定したCN(Common Name)と同じサーバ名を指定する。

server_name example.jp;

SSLを有効化 - ssl

sslディレクティブをonに設定すると、SSLが有効になる。ただし、listenディレクティブでsslパラメータを指定したときには不要。

ssl on;

サーバ証明書とプライベート鍵の指定 - ssl_certificateとssl_certificate_key

ssl_certificateディレクティブにサーバ証明書のファイルのパスを、ssl_certificate_keyディレクティブにプライベート鍵のファイルのパスを指定する。

ssl_certificate /etc/nginx/cert.pem;
ssl_certificate_key /etc/nginx/cert.key;

以上の設定をまとめると次のようになる。これらの設定を行えばSSLを利用できる。

server {
listen 443;
server_name example.jp;

ssl on;
ssl_certificate /etc/nginx/cert.pem;
ssl_certificate_key /etc/nginx/cert.key;
}

暗号に関する設定

使用するTLS/SSLのバージョンや暗号スイートについてはデフォルトの設定でも利用できるが、明示的に設定してみる。

使用するTLS/SSLのバージョン - ssl_protocols

ssl_protocolsには使用するSSLのバージョンを記述する。設定できるバージョンはSSLv2, SSLv3, TLSv1, TLSv1.1, TLSv1.2。
ただし、TLSv1.1とTLSv1.2はnginx 1.1.13以降および1.0.12以降でかつOpenSSL 1.0.1以降のときのみ動作する。

ssl_protocols SSLv3 TLSv1;

使用する暗号スイート - ssl_ciphers

ssl_ciphersにはSSLで使用する暗号スイートを指定する。デフォルト値はnginxのバージョンによって異なるが、nginx 1.2.0では"HIGH:!ADH:!MD5"になる。

「HIGH(公開鍵暗号の鍵長が128ビットより大きい)」、「aNULL(認証を提供しない暗号スイート)でない」、「MD5でない」ものを指定するにはと次のように記述する。
ssl_ciphers HIGH:!aNULL:!MD5;
参考までに、"openssl ciphers cipherlist '暗号スイートのリスト' -v"コマンドで利用できる暗号スイートの一覧を表示することができる。

$ openssl ciphers cipherlist 'HIGH:!aNULL:!MD5' -v

AES256-SHA SSLv3 Kx=RSA Au=RSA Enc=AES(256) Mac=SHA1
CAMELLIA256-SHA SSLv3 Kx=RSA Au=RSA Enc=Camellia(256) Mac=SHA1
PSK-AES256-CBC-SHA SSLv3 Kx=PSK Au=PSK Enc=AES(256) Mac=SHA1
AES128-SHA SSLv3 Kx=RSA Au=RSA Enc=AES(128) Mac=SHA1
CAMELLIA128-SHA SSLv3 Kx=RSA Au=RSA Enc=Camellia(128) Mac=SHA1
PSK-AES128-CBC-SHA SSLv3 Kx=PSK Au=PSK Enc=AES(128) Mac=SHA1

サーバが示した暗号スイートの優先 - ssl_prefer_server_ciphers

ssl_prefer_server_ciphersをonに指定すると、利用する暗号を選ぶ際に、SSLv3やTLSではサーバが示した暗号スイートが優先される。offにするとクライアントのものが優先される。デフォルトはoffです。onにするには次のように記述する。

ssl_prefer_server_ciphers on;

これはnginxの機能というよりはOpenSSLの機能で、SSL_CTX_set_options()にSSL_OP_CIPHER_SERVER_PREFERENCEを設定する。

SSLセッションキャッシュ

サーバの負荷を削減するために、SSLのセッションキャッシュを利用する設定を行う。

SSLセッションキャッシュの種類とサイズの指定 - ssl_session_cache

ssl_session_cacheにはSSLセッションキャッシュをどのように扱うかとそのキャッシュサイズを指定する。次のような文字列を指定することができる。

off セッションの再利用を明示的に禁止
none クライアントにはセッションの再利用を明示的には禁止しないが、実際は利用不可
builtin OpenSSL組み込みを利用。一つのワーカープロセスのみが利用可能。
shared すべてのワーカープロセスで共有。「shared:名前:サイズ」の形式で記述。

デフォルトはnone。

サーバの負荷を削減するためにはsharedを使うのが望ましい。例えば、キャッシュサイズを10MBに設定するには次のように記述する。
ssl_session_cache shared:SSL:10m;

SSLセッションキャッシュのタイムアウトの指定 - ssl_session_timeout

ssl_session_timeoutディレクティブにはSSLセッションキャッシュに保管するSSLセッションの情報のタイムアウト時間を指定する。デフォルトは"5m"(5分)です。例えば、10分に設定するには次のように記述する。

ssl_session_timeout 10m;

設定TIPS

HTTPとHTTPSの設定を共有

listenディレクティブにsslパラメータを付けると、そのポートでSSLを有効にして待ち受ける。この機能を使い、次のようにsslパラメータを付けない80番ポートを指定したlistenディレクティブとsslパラメータを付けた443番ポートを指定したlistenディレクティブを設定すると、同じバーチャルサーバの設定でHTTPとHTTPSの両方を有効にすることができる。
server {
listen 80;
listen 443 ssl;
server_name example.jp;
ssl_certificate /etc/nginx/cert.pem;
...
}

このときにはsslディレクティブを記述しない。TLS/SSLの有効・無効はlistenディレクティブのsslパラメータの有無で判断するようになる。もし、sslディレクティブでonを指定すると80番ポートでもTLS/SSLで待ち受けるようになってしまう。

IPベースのバーチャルサーバー

TLS/SSL対応のIPベースのバーチャルサーバを複数持つためには、次のようにバーチャルサーバ毎に待ち受ける異なるIPアドレスをlistenディレクティブに指定する。

server {
listen 192.0.2.1:443;
server_name example.jp;
ssl on;
ssl_certificate /etc/nginx/cert-example.jp.pem;
...
}

server {
listen 192.0.2.2:443;
server_name example.com;
ssl on;
ssl_certificate /etc/nginx/cert-example.com.pem;
...
}

名前ベースのバーチャルサーバー

従来のTLS/SSLのプロトコルでは、ハンドシェイクの際にクライアントはURIのホスト名の情報をサーバに渡すことができないため、サーバはどのバーチャルサーバに対するリクエストが判断できない。そのため、名前ベースのバーチャルサーバは利用できまない。しかし、Server Name Indication(以降、単にSNIと呼ぶ)というTLSの拡張機能により、ハンドシェイクの際にホスト名の情報を送ることができるようになった。ただし、このSNIを利用するためには、サーバとクライアントの両方がSNIをサポートしている必要がある。

nginx自体はSNIに対応しているが、SNIの機能を有効にしてビルドされている必要がある。SNIの機能が有効であるかは次のようなコマンドを実行して、"TLS SNI support enabled"という文字列が出力されるかでわかる。

$ nginx -V 2>&1 | grep SNI
TLS SNI support enabled

SNIが有効であるときには、クライアントがリクエストしたホスト名に対応したバーチャルサーバの設定が適応され、そのサーバ証明書が使われる。

server {
listen 443;
server_name example.jp;
ssl on;
ssl_certificate /etc/nginx/cert-example.jp.pem;
...
}

server {
listen 443;
server_name example.com;
ssl on;
ssl_certificate /etc/nginx/cert-example.com.pem;
...
}

なお、SNIが無効であるとき、あるいはクライアントがSNIに対応していないときには、デフォルトサーバのバーチャルサーバが適応され、そのサーバ証明書が使われる。

設定ファイルを変更する

[root@www ~]# vim /etc/nginx/conf.d/virtualhost.conf

サーバー名を変更し、index php を追加

server {
listen 80;
server_name arakawasan.com www.arakawasan.com;

#charset koi8-r;
#access_log /var/log/nginx/log/host.access.log main;

location / {
root /usr/share/nginx/html;
index index.html index.htm index.php;
}

# をすべて外し、script$/fastcgi_script_name; を /usr/share/nginx/html$fastcgi_script_name; に変更

location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html$fastcgi_script_name;
include fastcgi_params;
}

Nginx を再起動する

[root@www ~]# systemctl restart nginx

[root@www ~]# systemctl status nginx

● nginx.service - nginx - high performance web server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: active (running) since 月 2016-01-25 14:07:53 JST; 12s ago
Docs: http://nginx.org/en/docs/
Process: 22998 ExecStop=/bin/kill -s QUIT $MAINPID (code=exited, status=0/SUCCESS)
Process: 23007 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
Process: 23004 ExecStartPre=/usr/sbin/nginx -t -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
Main PID: 23009 (nginx)
CGroup: /system.slice/nginx.service
├─23009 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx....
├─23010 nginx: worker process
├─23011 nginx: worker process
└─23012 nginx: worker process

オレオレ証明書を使用した SSL 設定


OpenSSL ライブラリをインストールする

[root@www ~]## yum -y install openssl

パッケージ 1:openssl-1.0.1e-51.el7_2.2.x86_64 はインストール済みか最新バージョンです
何もしません

秘密鍵を作成する

[root@www ~]## openssl genrsa 2048 > server.key

証明書署名要求(CSR / Certificate Signing Request)を作成する

[root@www ~]## openssl req -new -key server.key > server.csr

You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:JP
State or Province Name (full name) []:
Locality Name (eg, city) [Default City]:
Organization Name (eg, company) [Default Company Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:weblabo.oscasierra.net
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

※ほとんどEnterでスキップ

サーバ証明書の作成(上で作成した自分の秘密鍵 (server.key) で署名し、有効期限が10年(3650日)ある証明書を作成)する

[root@www ~]# openssl x509 -days 3650 -req -signkey server.key < server.csr > server.crt

Signature ok
subject=/C=JP/L=Default City/O=Default Company Ltd
Getting Private key

これでサーバ証明書が server.crt というファイル名で作成された。 このファイルを WEB サーバなどに設定すれば HTTPS の通信ができる。

サーバ証明書を設定ダイレクトリーに保存する

[root@www ~]## sudo mv server.* /etc/nginx/conf.d/

ダイレクトリーへ移動する

[root@www ~]## cd /etc/nginx/conf.d/

所有者を変更する

[root@www ~]# sudo chown root:root server.*

フォルダーの中にダイレクトリーがあるか確認する

[root@www ~]# vim /etc/nginx/nginx.conf

http {

(中略)

gzip on;

include /etc/nginx/conf.d/*.conf;
}
[root@www ~]# systemctl restart nginx

[root@www ~]# systemctl status nginx

/etc/nginx/conf.d/default.conf の編集


設定ファイルを変更する

[root@www ~]# # vim /etc/nginx/conf.d/default.conf

ポートとサーバー名を変更し、index php を追加

server {
listen 443;
server_name arakawasan.com www.arakawasan.com;
ssl on;
ssl_certificate /etc/nginx/conf.d/server.crt;
ssl_certificate_key /etc/nginx/conf.d/server.key;
#charset koi8-r;
#access_log /var/log/nginx/log/host.access.log main;

location / {
root /usr/share/nginx/html;
index index.html index.htm index.php;
}

# をすべて外し、script$/fastcgi_script_name; を /usr/share/nginx/html$fastcgi_script_name; に変更

location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scri$fastcgi_script_name;
include fastcgi_params;
}

プログラムの構文にエラーがないかシンタックスチェックで調べる

[root@www ~]# nginx -t

Nginx を再起動する

[root@www ~]# systemctl restart nginx

[root@www ~]# systemctl status nginx

● nginx.service - nginx - high performance web server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: active (running) since 月 2016-01-25 14:30:06 JST; 44s ago
Docs: http://nginx.org/en/docs/
Process: 23614 ExecStop=/bin/kill -s QUIT $MAINPID (code=exited, status=0/SUCCESS)
Process: 23622 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
Process: 23619 ExecStartPre=/usr/sbin/nginx -t -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
Main PID: 23624 (nginx)
CGroup: /system.slice/nginx.service
├─23624 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx....
├─23625 nginx: worker process
├─23626 nginx: worker process
└─23627 nginx: worker process

Nginx が SSL 有効かを確認する

[root@www ~]# nginx -V

下記の表示を確認する
TLS SNI support enabled(前略)--with-http_ssl_module (略)

Port の開通を確認する

[root@www ~]# ss -nat

State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 127.0.0.1:9000 *:*
LISTEN 0 128 *:80 *:*
LISTEN 0 128 *:443 *:*
LISTEN 0 128 *:22022 *:*
TIME-WAIT 0 0 127.0.0.1:9000 127.0.0.1:52948
ESTAB 0 0 49.212.133.20:22022 42.145.42.124:40723
TIME-WAIT 0 0 127.0.0.1:9000 127.0.0.1:52946
ESTAB 0 0 49.212.133.20:22022 42.145.42.124:35713
ESTAB 0 0 49.212.133.20:22022 42.145.42.124:33950
TIME-WAIT 0 0 127.0.0.1:9000 127.0.0.1:52947
ESTAB 0 0 49.212.133.20:443 42.145.42.124:37402
ESTAB 0 0 49.212.133.20:22022 42.145.42.124:45495
ESTAB 0 0 49.212.133.20:22022 42.145.42.124:41222
TIME-WAIT 0 0 127.0.0.1:9000 127.0.0.1:52949
ESTAB 0 36 49.212.133.20:22022 42.145.42.124:45423
ESTAB 0 0 49.212.133.20:22022 42.145.42.124:37389
ESTAB 0 0 49.212.133.20:22022 42.145.42.124:42578
ESTAB 0 0 49.212.133.20:22022 42.145.42.124:42365
LISTEN 0 80 :::3306 :::*
LISTEN 0 128 :::22022 :::*

php7の設定
設定ファイルをバックアップする

[root@www ~]# cp /etc/php.ini /etc/php.ini.org

動作確認のために、phpinfoを表示するファイルをドキュメントルート直下に置く

[root@www ~]# vim /usr/share/nginx/html/phpinfo.php

<?php
phpinfo();
?>

safariから http(s)://www.arakawasan.com/phpinfo.php にアクセスして、動作確認する

不明


PHP Version 7.0.2
System Linux www.arakawasan.com 4.4.0-1.el7.elrepo.x86_64 #1 SMP Sun Jan 10 21:17:16 EST 2016 x86_64
Build Date Jan 6 2016 15:25:50
Server API FPM/FastCGI
Virtual Directory Support disabled
Configuration File (php.ini) Path /etc
Loaded Configuration File /etc/php.ini
Scan this dir for additional .ini files /etc/php.d
Additional .ini files parsed /etc/php.d/10-opcache.ini, /etc/php.d/15-xdebug.ini, /etc/php.d/20-bcmath.ini, /etc/php.d/20-bz2.ini, /etc/php.d/20-calendar.ini, /etc/php.d/20-ctype.ini, /etc/php.d/20-curl.ini, /etc/php.d/20-dom.ini, /etc/php.d/20-exif.ini, /etc/php.d/20-fileinfo.ini, /etc/php.d/20-ftp.ini, /etc/php.d/20-gd.ini, /etc/php.d/20-gettext.ini, /etc/php.d/20-gmp.ini, /etc/php.d/20-iconv.ini, /etc/php.d/20-intl.ini, /etc/php.d/20-json.ini, /etc/php.d/20-ldap.ini, /etc/php.d/20-mbstring.ini, /etc/php.d/20-mcrypt.ini, /etc/php.d/20-mysqlnd.ini, /etc/php.d/20-pdo.ini, /etc/php.d/20-pgsql.ini, /etc/php.d/20-phar.ini, /etc/php.d/20-posix.ini, /etc/php.d/20-shmop.ini, /etc/php.d/20-simplexml.ini, /etc/php.d/20-sockets.ini, /etc/php.d/20-sqlite3.ini, /etc/php.d/20-sysvmsg.ini, /etc/php.d/20-sysvsem.ini, /etc/php.d/20-sysvshm.ini, /etc/php.d/20-tokenizer.ini, /etc/php.d/20-xml.ini, /etc/php.d/20-xmlwriter.ini, /etc/php.d/20-xsl.ini, /etc/php.d/30-mysqli.ini, /etc/php.d/30-pdo_dblib.ini, /etc/php.d/30-pdo_mysql.ini, /etc/php.d/30-pdo_pgsql.ini, /etc/php.d/30-pdo_sqlite.ini, /etc/php.d/30-wddx.ini, /etc/php.d/30-xmlreader.ini, /etc/php.d/40-apcu.ini, /etc/php.d/40-imagick.ini, /etc/php.d/40-msgpack.ini, /etc/php.d/50-apc.ini, /etc/php.d/50-memcached.ini
PHP API 20151012
PHP Extension 20151012
Zend Extension 320151012
Zend Extension Build API320151012,NTS
PHP Extension Build API20151012,NTS
Debug Build no
Thread Safety disabled
Zend Signal Handling disabled
Zend Memory Manager enabled
Zend Multibyte Support provided by mbstring
IPv6 Support enabled
DTrace Support enabled
Registered PHP Streams https, ftps, compress.zlib, php, file, glob, data, http, ftp, compress.bzip2, phar
Registered Stream Socket Transports tcp, udp, unix, udg, ssl, sslv3, sslv2, tls, tlsv1.0, tlsv1.1, tlsv1.2
Registered Stream Filters zlib.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk, bzip2.*, convert.iconv.*, mcrypt.*, mdecrypt.*

設定ファイルを編集する

[root@www ~]# vim /etc/php.ini
359行目 expose_phpをOnからOffへ変更
expose_php = Off

378行目 max_input_time を 60 から 600へ変更
max_input_time = 600

656行目、post_max_sizeを10Gに変更。
post_max_size = 10000M

676行目 ;default_charsetの;を消し、UTF-8に変更default_charset = "UTF-8"

799行目 upload_max_filesizeを2Mから10Gに拡大
upload_max_filesize = 10000M

877行目 ;date.timezoneの;を消し、Asia/Tokyoを追加date.timezone = "Asia/Tokyo"

1465行目、;mbstring.language の;を消して有効化
mbstring.language = Japanese

1472行目 ;mbstring.internal_encoding の;を消し、UTF-8に変更
mbstring.internal_encoding = UTF-8

1480行目、;mbstring.http_input の;を消して有効化
mbstring.http_input = pass

1490行目 ;mbstring.http_output の;を消して有効化
mbstring.http_output = pass

1498行目 ;;mbstring.encoding_translation の;を消して有効化
mbstring.encoding_translation = Off

1503行目 ;mbstring.detect_orderの;を消して有効化
mbstring.detect_order = auto

設定を反映するためにNginxを再起動する

[root@www ~]# systemctl restart nginx

[root@www ~]# systemctl status nginx

[root@www ~]# php -m | grep mysql

PHP Warning: Module 'mysqlnd' already loaded in Unknown on line 0

mysqli
mysqlnd
pdo_mysql

[root@www ~]# php -i | grep socket

/etc/php.d/20-sockets.ini,
mysqli.default_socket => /var/lib/mysql/mysql.sock => /var/lib/mysql/mysql.sock
pdo_mysql.default_socket => /var/lib/mysql/mysql.sock => /var/lib/mysql/mysql.sock
sockets
default_socket_timeout => 60 => 60

PHP-FPMの設定


設定ファイルをバックアップする

[root@www ~]# cp -a /etc/php-fpm.d/www.conf /etc/php-fpm.d/www.conf.org

php-fpmのバージョンを確認する

[root@www ~]# php -v

PHP 7.0.2 (fpm-fcgi) (built: Jan 6 2016 15:25:52)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2015 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies
with Xdebug v2.4.0RC3, Copyright (c) 2002-2015, by Derick Rethans

php-fpm の設定を変更する

[root@www ~]# vim /etc/php-fpm.d/www.conf

24行目:変更
user = apache

user = nginx

26行目:変更
group = apache

group = nginx

php-fpm を起動、自動起動を有効化する

[root@www ~]# systemctl start php-fpm

[root@www ~]# systemctl enable php-fpm

自動起動設定を確認する

[root@www ~]# systemctl list-unit-files | grep php-fpm

php-fpm.service enabled

php-fpm の稼働状況を確認する

[root@www ~]# systemctl status php-fpm

● php-fpm.service - The PHP FastCGI Process Manager
Loaded: loaded (/usr/lib/systemd/system/php-fpm.service; enabled; vendor preset: disabled)
Active: active (running) since 日 2016-01-24 13:54:01 JST; 1 day 5h ago
Main PID: 12982 (php-fpm)
Status: "Processes active: 0, idle: 6, Requests: 1024, slow: 0, Traffic: 0.2req/sec"
CGroup: /system.slice/php-fpm.service
├─12982 php-fpm: master process (/etc/php-fpm.conf)
├─12983 php-fpm: pool www
├─12984 php-fpm: pool www
├─12985 php-fpm: pool www
├─12986 php-fpm: pool www
├─12987 php-fpm: pool www
└─24388 php-fpm: pool www

以下を確認する

listen = 127.0.0.1:9000
listen.allowed_clients = 127.0.0.1
(;を外す)listen.owner = (nobodyを変更)nginx
(;を外す)listen.group = (nobodyを変更)nginx

user = nginx
group = nginx

pm = dynamic
pm.max_children = 15(50のままにした)
pm.start_servers = 5(5のままにした)
pm.min_spare_servers = 2(5のままにした)pm.max_spare_servers = 5(35のままにした)

slowlog = /var/log/php-fpm/www-slow.log

php_admin_value[error_log] = /var/log/php-fpm/www-error.log
php_admin_flag[log_errors] = on

php_value[session.save_handler] = files
php_value[session.save_path] = /var/lib/php/session
php_value[soap.wsdl_cache_dir] = /var/lib/php/wsdlcache

session-path ダイレクトリーを作成する

[root@www ~]# mkdir -p /var/lib/php/session

[root@www ~]# chown nginx:nginx -R /var/lib/php/session/

php-fpm を再起動する

[root@www ~]# systemctl restart php-fpm.service

MariaDBの設定


バージョンを確認する

[root@www ~]# mysql --version

mysql Ver 15.1 Distrib 10.1.10-MariaDB, for Linux (x86_64) using readline 5.1

mysql にログインする

[root@www ~]# mysql -u root -p

Enter password: xxxxxxxxxx

Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 6
Server version: 10.1.10-MariaDB MariaDB Server

Copyright (c) 2000, 2015, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> select version();
+-----------------+
| version() |
+-----------------+
| 10.1.10-MariaDB |
+-----------------+
1 row in set (0.00 sec)

MariaDB [(none)]> exit
Bye

MariaDB (MySQL)を初期設定する

[root@www ~]# mysql_secure_installation

Change the root password? [Y/n] n
... skipping.
Remove anonymous users? [Y/n] Y
... Success!
Disallow root login remotely? [Y/n] Y
... Success!
Remove test database and access to it? [Y/n] Y
... Success!
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!

MariaDB を再起動する

[root@www ~]# systemctl restart mariadb

Verify MySQL is now MariaDB by using the command client
mysql

MariaDB の稼働状況を確認する

[root@www ~]# systemctl status mariadb

● mariadb.service - MariaDB database server
Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
Drop-In: /etc/systemd/system/mariadb.service.d
└─migrated-from-my.cnf-settings.conf
Active: active (running) since 月 2016-01-25 23:16:55 JST; 11s ago
Main PID: 26971 (mysqld)
Status: "Taking your SQL requests now..."
CGroup: /system.slice/mariadb.service
└─26971 /usr/sbin/mysqld

root で常に vim を使いシンタックスハイライトを有効にするため、.bashrc に登録する

[kenjiarakawa@www ~]$ vi .bashrc

alias vi='vim' を追加する

設定ファイルをバックアップする

[root@www ~]# cp -a /etc/my.cnf /etc/my.cnf.org

[root@www ~]# cp -a /etc/my.cnf.d/server.cnf /etc/my.cnf.d/server.cnf.org

[root@www ~]# cp -a /etc/my.cnf.d/mysql-clients.cnf /etc/my.cnf.d/mysql-clients.cnf.org

[root@www ~]# cp -a /etc/my.cnf.d/server.cnf.rpmsave /etc/my.cnf.d/server.cnf.rpmsave.org

デフォルト設定ファイルを my.cnf にコピーする

[root@www ~]# cp -a /usr/share/mysql/my-huge.cnf /etc/my.cnf

my.cnf を編集する

[root@www ~]# vim /etc/my.cnf

[mysqld]

skip-character-set-client-handshake ← 追加(どんな要求が来ても文字コードを変換せずUTF-8で応答を返す)

character-set-server = utf8 ← 追加(MariaDBサーバーの文字コードをUTF-8にする)

thread_cache_size = 50← 変更(8 > 50)

thread_concurrency = 6 ← 変更(8 > 6)

log_error = /var/log/mysql/error.log ← 追加

/var/log/mysql/error.log を作成する

[root@www ~]# mkdir /var/log/mysql/

[root@www ~]# cd /var/log/mysql/

[root@www mysql]# touch error.log

MariaDB を再起動する

[root@www ~]# systemctl restart mariadb

設定変更を確認する

[root@www ~]# mysql -u root -p

Enter password: xxxxxxxxxx

MariaDB [(none)]> show variables like 'char%';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

MariaDB [(none)]> status
--------------
mysql Ver 15.1 Distrib 10.1.10-MariaDB, for Linux (x86_64) using readline 5.1

Connection id: 3
Current database:
Current user: root@localhost
SSL: Not in use
Current pager: stdout
Using outfile: ''
Using delimiter: ;
Server: MariaDB
Server version: 10.1.10-MariaDB-log MariaDB Server
Protocol version: 10
Connection: Localhost via UNIX socket
Server characterset: utf8
Db characterset: utf8
Client characterset: utf8
Conn. characterset: utf8
UNIX socket: /var/lib/mysql/mysql.sock
Uptime: 1 min 13 sec

Threads: 1 Questions: 5 Slow queries: 0 Opens: 0 Flush tables: 1 Open tables: 11 Queries per second avg: 0.068
--------------

MariaDB [(none)]> exit
Bye

WordPressで使用するデータベース、ユーザーを作成する

[root@www ~]# mysql -u root -p

Enter password:

MariaDB [(none)]> create database wordpress character set utf8;
Query OK, 1 row affected (0.00 sec)

MariaDB [(none)]> grant all privileges on wordpress.* to kexxxxxxxxxx@www.arakawasan.com identified by ‘XXXXXXXXXXXX’;
Query OK, 0 rows affected (0.01 sec)

MariaDB [(none)]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> exit
Bye

データベースwordpressが作成されたことを確認する

MariaDB [(none)]> show databases;

+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| wordpress |
+--------------------+
4 rows in set (0.00 sec)

MariaDBでデータベース操作をする

[root@www ~]# mysql -u root -p

MariaDB [(none)]> create database test;
Query OK, 1 row affected (0.00 sec)

MariaDB [(none)]> show databases;

+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| test |
| wordpress |
+--------------------+
5 rows in set (0.00 sec)

MariaDB [(none)]> use test;

Database changed

MariaDB [test]> create table test(num int,name varchar(50));
Query OK, 0 rows affected (0.01 sec)

MariaDB [test]> show tables;

+----------------+
| Tables_in_test |
+----------------+
| test |
+----------------+
1 row in set (0.00 sec)

MariaDB [test]> insert into test values(1,'ユニックスユーザ1');
Query OK, 1 row affected (0.00 sec)

MariaDB [test]> insert into test values(2,'ユニックスユーザ2');
Query OK, 1 row affected (0.00 sec)

MariaDB [test]> select * from test;

+------+---------------------------+
| num | name |
+------+---------------------------+
| 1 | ユニックスユーザ1 |
| 2 | ユニックスユーザ2 |
+------+---------------------------+
2 rows in set (0.01 sec)

MariaDB [test]> update test set name='ユニックスユーザ10' where num=2;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

MariaDB [test]> select * from test;

+------+----------------------------+
| num | name |
+------+----------------------------+
| 1 | ユニックスユーザ1 |
| 2 | ユニックスユーザ10 |
+------+----------------------------+
2 rows in set (0.00 sec)

MariaDB [test]> delete from test where num=1;
Query OK, 1 row affected (0.00 sec)

MariaDB [test]> select * from test;

+------+----------------------------+
| num | name |
+------+----------------------------+
| 2 | ユニックスユーザ10 |
+------+----------------------------+
1 row in set (0.00 sec)

MariaDB [test]> drop table test;
Query OK, 0 rows affected (0.01 sec)

MariaDB [test]> show tables;
Empty set (0.00 sec)

MariaDB [test]> drop database test;
Query OK, 0 rows affected (0.01 sec)

MariaDB [(none)]> show databases;
+--------------------+
| Database |
+--------------------+
| db_wordpress |
| information_schema |
| mysql |
| performance_schema |
| wordpress |
+--------------------+
5 rows in set (0.00 sec)

MariaDB [(none)]> exit
Bye

MariaDBのバックアップとリストアをする

データベース全体をdump.sqlに吐き出す

[root@www ~]# mysqldump -u root -p -x --all-databases > dump.sql
Enter password:

特定のデータベース(mysql)を指定してファイルに吐き出す

[root@www ~]# mysqldump -u root -p mysql > mysql.dump.sql
Enter password:

特定のデータベース(wordpress)を指定してファイルに吐き出す

[root@www ~]# mysqldump -u root -p wordpress > wordpress.dump.sql
Enter password:

データベース全体をリストアする

[root@www ~]# mysql -u root -p < dump.sql
Enter password:

特定のデータベースを指定してデータベースをリストアする

[root@www ~]# mysql -u root -p mysql < mysql.dump.sql
Enter password:

Nginx の設定 - Wordpress のインストール


/etc/nginx/conf.d/wordpress.conf の編集

設定ファイルをバックアップする

[root@www ~]# cp /etc/nginx/conf.d/default.conf.org /etc/nginx/conf.d/wordpress.conf

Wordpressを入手する

[root@www ~]# wget https://ja.wordpress.org/wordpress-4.4.1-ja.tar.gz

2016-01-26 01:15:44 (5.82 MB/s) - `wordpress-4.4.1-ja.tar.gz' へ保存完了 [7557890/7557890]

ファイルを解凍する

[root@www ~]# tar xvzf wordpress-4.4.1-ja.tar.gz

ファイルの所有者を変更する

[root@www ~]# chown -R nginx:nginx wordpress

mvでダイレクトリーごと上書きするため、移動先を空にする

[root@www ~]# rm -rf /usr/share/nginx/wordpress/*

Wordpress ダイレクトリーを移動する

[root@www ~]# mv wordpress /usr/share/nginx/html

nginx の設定

[root@www ~]# vim /etc/nginx/conf.d/wordpress.conf

Wordpress ルートダイレクトリーを変更する

location / {
root /usr/share/nginx/html/wordpress;
index index.php;
}

パーマリンク設定

location /wordpress {
try_files $uri $uri/ /wordpress/index.php?$args;
}

urlの末尾に/が付いていない場合に付与する

location ~ /wp-admin$ {
rewrite /wp-admin$ $scheme://$host$uri/ permanent;
}

Wordpress サーバーの構築


wp-config.php をコピーする

[root@www ~]# cp /usr/share/nginx/html/wordpress/wp-config.php /usr/share/nginx/html/wordpress/wp-config.php.org

wp-config.php を編集する

[root@www ~]# vim /usr/share/nginx/html/wordpress/wp-config.php

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

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

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

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

下記コードを追加
define('FORCE_SSL_ADMIN', true);
if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
$_SERVER['HTTPS']='on';

Nginxの設定(バーチャルホスト設定)

設定を確認する

nginx -t

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Wordpress をルートダイレクトリーで表示する


さくらVPSでFTPを使う

vsftpdをインストールする

[root@www ~]# yum install vsftpd

インストール:
vsftpd.x86_64 0:3.0.2-10.el7

完了しました!

vsftpdを自動起動する

[root@www ~]# systemctl enable vsftpd.service

設定ファイルをバックアップする

[root@www ~]# cp /etc/vsftpd/vsftpd.conf /etc/vsftpd/vsftpd.conf.org

設定ファイルを編集する

[root@www ~]# vim /etc/vsftpd/vsftpd.conf

#anonymous_enable =YES
anonymous_enable=NO #不特定多数のユーザからのアクセスを拒否する

#ascii_upload_enable =YES
ascii_upload_enable=YES #アスキーモードのアップロードを許可する
#ascii_download_enable =YES
ascii_download_enable=YES #アスキーモードのダウンロードを許可する

#ftpd_banner =Welcome to blah FTP service.
ftpd_banner=Welcome to blah FTP service. #シグニチャを隠蔽する

#chroot_local_user =YES
chroot_local_user=YES #許可したユーザ以外のホームディレクトリより上層へのアクセスを禁止する
#chroot_list_enable =YES
chroot_list_enable=YES #ホームディレクトリより上層へアクセスできるユーザリストを有効にする
chroot_list_file=/etc/vsftpd/chroot_list

#ls_recurse_enable =YES
ls_recurse_enable=YES #ディレクトリの削除を許可する

#以下 ,追記
userlist_enable=YES #許可するユーザのみをuserlist_fileで指定する
userlist_deny=NO
userlist_file=/etc/vsftpd/user_list
local_root=/usr/share/nginx/html #ホームディレクトリを指定する
use_localtime=YES #タイムスタンプに現地時間を用いる

ホームディレクトリより上層へアクセス可能なユーザリストを作成する

[root@www ~]# vim /etc/vsftpd/chroo_list

kexxxxxxxxxx を追加する

ftpでアクセス可能なユーザリストを作成する

[root@www ~]# vim /etc/vsftpd/user_list

kexxxxxxxxxx を追加する

ルートディレクトリの所有者を変更する

[root@www ~]# chown -R kenjiarakawa:kenjiarakawa /usr/share/nginx/html

ファイアーウォールの設定を変更してftpのポート(21番)を空ける

[root@www ~]# firewall-cmd --permanent --zone=public --add-port=21/tcp

success

[root@www ~]# firewall-cmd --add-service=ftp --zone=public --permanent

success

ファイアーウォールを再起動する

[root@www ~]# systemctl restart firewalld

[root@www ~]# firewall-cmd --list-all

public (default, active)
interfaces: eth0
sources:
services: dhcpv6-client ftp http https ssh
ports: 33033/tcp 21/tcp
masquerade: no
forward-ports:
icmp-blocks:
rich rules:

vsftpdを再起動する

[root@www ~]# systemctl restart vsftpd.service

パスワードを設定する

[root@www ~]# passwd kexxxxxxxxxx

サーバーにFTPでアクセスして .htacces が設置されていることを確認する

.htacces が存在しない場合は、新しいファイルを作成し次のコードを記載する

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

サブダイレクトリーにある index.php をルートダイレクトリーにコピーする

[root@www ~]# cp /usr/share/nginx/html/wordpress/index.php /usr/share/nginx/html/index.php

コピーしたファイルを変更する

[root@www ~]# vim /usr/share/nginx/html/index.php

17行目

修正前:
require( dirname( __FILE__ ) . '/wp-blog-header.php' );

修正後:WordPress コアファイルの新ディレクトリ名を使います
require( dirname( __FILE__ ) . '/wordpress/wp-blog-header.php' );

ルートフォルダにあるindex.htmlというののファイル名をindex2.htmlに書き換える

[root@www ~]# mv /usr/share/nginx/html/index.html /usr/share/nginx/html/index2.html

Nginx を再起動する

[root@www ~]# systemctl restart nginx

ワードプレスのダッシュボードでの設定

ワードプレスの管理画面にログインして、「設定」→「一般」と進む

ここで「WordPress アドレス (URL)」と「サイトアドレス (URL)」の箇所を見ると、次のように記載されている

WordPress アドレス (URL) http://www.arakawasan.com/wordpress/
サイトアドレス (URL) http://www.arakawasan.com/wordpress/

下の「サイトアドレス (URL) 」のほうを表示させたいドメイン直下のURLに変更する

WordPress アドレス (URL) http://www.arakawasan.com/wordpress/
サイトアドレス (URL) http://www.arakawasan.com/

この記事が気に入ったらサポートをしてみませんか?