[技術ブログvol.25] Nginx + PHP-FPM でWrodPressを動かそう

はじめに

WordPressといえばよく知られているCMSです。
多くの場合Apache+mod_phpを利用して動作しているとおもわれます。
今回はあえてApacheを使わずNginxとPHP-FPMでWordPressを動かしてみたいと思います。

今回は、nginxの細かなチューニング等は行っていません。
まずはWordPressが動く設定を作っていきます。

今回の環境

今回の環境は以下の通りです。
Nginxを除いてCentOS標準レポジトリからyumコマンドでインストールできるものを利用します。

  • OS: CentOS 6.6
  • Nginx 1.6.2
  • PHP 5.3.3
  • MySQL 5.1
  • vsftpd 2.2.2

Nginxのインストール

今回はビルドの手間を省くためNginx公式レポジトリよりyumコマンドでインストールを行います。
注意点としてはNginxはApacheと異なり動的にモジュールの追加、削除が行えません。
サードパーティのモジュールを組み込みたいといった場合やメール等の不要なモジュールを除きたいといった場合は独自にビルドする必要があります。

Nginxレポジトリの追加

Nginxインストール用yumレポジトリを追加します。
追加方法は以下のコマンド一発で可能です。

# rpm -ivh http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm

問題なくインストールできているか確認

# cat /etc/yum.repos.d/nginx.repo

# nginx.repo

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

エラーなくファイルが表示されればひとまずOKです。

Nginx本体のインストール
# yum install -y nginx

以上で終了です。

Nginxに組み込まれているモジュールの確認
# nginx -V
nginx version: nginx/1.6.2
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-3) (GCC)
TLS SNI support enabled
configure arguments:
--prefix=/etc/nginx
--sbin-path=/usr/sbin/nginx
--conf-path=/etc/nginx/nginx.conf
--error-log-path=/var/log/nginx/error.log
--http-log-path=/var/log/nginx/access.log
--pid-path=/var/run/nginx.pid
--lock-path=/var/run/nginx.lock
--http-client-body-temp-path=/var/cache/nginx/client_temp
--http-proxy-temp-path=/var/cache/nginx/proxy_temp
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp
--http-scgi-temp-path=/var/cache/nginx/scgi_temp
--user=nginx
--group=nginx
--with-http_ssl_module
--with-http_realip_module
--with-http_addition_module
--with-http_sub_module
--with-http_dav_module
--with-http_flv_module
--with-http_mp4_module
--with-http_gunzip_module
--with-http_gzip_static_module
--with-http_random_index_module
--with-http_secure_link_module
--with-http_stub_status_module
--with-http_auth_request_module
--with-mail
--with-mail_ssl_module
--with-file-aio
--with-ipv6
--with-http_spdy_module
--with-cc-opt='-O2 -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic'

組み込まれているモジュールに問題がなければこれで完了です。
ここでもし他に組み込みたいモジュールがある、メール系のモジュールが入ってるけど使わないので組み込みたくない等の場合はソースやSRPMを使ってコンフィグオプションを変更してビルドし直す必要があります。
そのような場合は適宜コンフィグオプションを変更しビルドしてください。

MySQLインストールとセットアップ

MySQLのインストール

今回はCentOS標準レポジトリにあるMySQL5.1を利用します。

# yum install -y mysql mysql-server
mysqldの起動
# service mysqld start
初期セットアップ

今回はDBも同じサーバに設置するのでmysql_secure_installationコマンドを利用して初期設定を行います。

# mysql_secure_installation

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


In order to log into MySQL to secure it, we'll need the current
password for the root user. If you've just installed MySQL, 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 MySQL
root user without the proper authorisation.

Set root password? [Y/n] y ←rootパスワード設定するかどうかyを入力
New password: ←rootのパスワードを入力
Re-enter new password: ←再度同じrootのパスワードを入力
Password updated successfully!
Reloading privilege tables..
... Success!


By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL 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 ←匿名ユーザを削除するかどうか。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 ←外部からrootログインを無効にするかどうか y を入力
... Success!

By default, MySQL 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 ←ユーザ権限が保存されているテーブルをリロードするか y を入力
... Success!

Cleaning up...



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

Thanks for using MySQL!

PHPのインストール

PHPもCentOS標準レポジトリで提供されているものを利用します。
PHP5.3はEOLとなっていますが、標準レポジトリで提供されているPHPはCentOSのメンテナの人たちが脆弱性などのパッチ適用を行っているため基本的には利用に問題ありません。

yumコマンドでphpをインストール
# yum install -y php php-mbstring php-mysql php-fpm
php.iniをバックアップ
# cp -p /etc/php.ini{,.org}
php.iniを編集

タイムゾーンを設定

# perl -pi -e 's/^;date.timezone =/date.timezone = "Asia/Tokyo"/' /etc/php.ini

イースターエッグを無効化

# perl -pi -e 's/^expose_php = On/expose_php = Off/' /etc/php.ini
mysqlのデータベース作成
mysqlにrootでログイン
# mysql -u root -p
Enter password:
wordpress用DBの作成
mysql> create database wordpress ;
Query OK, 1 row affected (0.00 sec)
wordpress用ユーザの作成
mysql> grant all privileges on wordpress.* to wordpress@localhost identified by 'PASSWORD';
Query OK, 0 rows affected (0.00 sec)


mysql> exit

plugin

Nginxの設定
ディレクトリの作成
mkdir -p /var/www/html
nginxの設定
オリジナルファイルをバックアップ
cp -p /etc/nginx/nginx.conf{,.org}
nginx.confの設定
# vim /etc/nginx/nginx.conf


user nginx;
worker_processes auto; # コア数に合わせてwarkerプロセス数を自動で決める

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


events {
worker_connections 1024;
use epoll;
}


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;

keepalive_timeout 65;

#gzip on;

include /etc/nginx/conf.d/*.conf;
}
wordpress 配信用の設定

wordpress用の設定ファイルは/etc/nginx/conf.d/に設置します。

vim /etc/nginx/conf.d/wordpress.conf


server {
listen 80;
server_name www.example.com;
root /var/www/html;

index index.php;

access_log /var/log/nginx/www.example.com.access.log main;
error_log /var/log/nginx/www.example.com.error.log error;

ocation = /favicon.ico {
log_not_found off;
access_log off;
}

location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}

location ~ /. {
deny all;
}

location ~* /(?:uploads|files)/.*.php$ {
deny all;
}


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

rewrite /wp-admin$ $scheme://$host$uri/ permanent;

location ~* ^.+.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf|js|JS|css|html?)$ {
access_log off;
log_not_found off;
expires 1d;
}

location ~ [^/].php(/|$) {
fastcgi_split_path_info ^(.+?.php)(/.*)$;
if (!-f $document_root$fastcgi_script_name) {
return 404;
}

include fastcgi_params;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass 127.0.0.1:9000;
}
}
php-fpmの設定
設定ファイルのバックアップ
cp -p /etc/php-fpm.d/www.conf{,.org}
実行ユーザとグループをapacheからnginxに置換
perl -pi -e 's/user = apache/user = nginx/' www.conf
perl -pi -e 's/group = apache/group = nginx/' www.conf
WordPress の設置
ZIPファイルのダウンロード
cd /usr/local/src/

wget https://ja.wordpress.org/wordpress-4.1.1-ja.zip
解凍して設置
unzip -q wordpress-4.1.1-ja.zip

cp -a wordpress/* /var/www/html/
wp-config.phpの設定
cd /var/www/html/

cp -p wp-config-sample.php wp-config.php

vim wp-config.php

※変更箇所のみ記載

/** WordPress のためのデータベース名 */
define('DB_NAME', 'wordpress');

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

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

/** 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');

※認証ユニークキーは https://api.wordpress.org/secret-key/1.1/salt/ にアクセスして表示されたものを書き込む

wordpress各ファイルのオーナとグループを変更
chown nginx. -R *
WEBアクセス

http://www.example.com/にアクセスしてWordPressのインストール画面が表示されれば完了。

あとは設定を行っていくだけです。

技術ブログ中の人
NginxやPHP-FPMの設定の最適化についても、引き続き書いていこうと思います。

返信を残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA