在樱花VPS(CentOS7)上,搭建Nginx+PHP7.1(7.3)+MariaDB的WordPress网站(支持HTTPS)
当我试图将樱花VPS的计划从1GB升级到2GB时,发现我当前的v3套餐不支持此操作,所以我从头开始重新搭建了服务器。我会在下面以备忘录的形式记录下当时的步骤。
2019/09/29
我写了一篇关于搭建“Nginx+PHP7.1+MariaDB的phpMyAdmin”的续集文章。
各种版本等如下所示。
-
- CentOS Linux release 7.2.1511 (Core)
-
- nginx version: nginx/1.12.1
-
- PHP 7.1.8 (cli) (built: Aug 2 2017 12:13:05) ( NTS )
- mysql Ver 15.1 Distrib 10.2.7-MariaDB, for Linux (x86_64) using readline 5.1
不管怎样,签订了v4的2GB套餐并开始使用。
另外,如果命令的开头是#,表示超级用户,如果是$,则表示普通用户(可以使用sudo su root命令)。
重新安装操作系统(CentOS7)
由于Sakura VPS的初始操作系统是“CentOS 6(x86_64)”,因此将安装“CentOS 7 x86_64”。
只需在控制面板的右上角选择“各种设置”,然后选择“操作系统安装”,并按照屏幕上的指示进行操作即可。

可以选择作为“标准操作系统”。

最初的设置(如安全方面等)
登录
$ ssh root@xx.xxx.xxx.xx
或者
$ ssh root@hoegehoge.com
创建用户
暂时先创建admin账号。
# useradd admin
# passwd admin
Changing password for user admin.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
由于我想要使用sudo命令,因此我将添加到wheel用户组中。
# id admin
uid=1000(admin) gid=1000(admin) groups=1000(admin)
# usermod -G wheel admin
# id admin
uid=1000(admin) gid=1000(admin) groups=1000(admin),10(wheel)
在visudo中,有时候可以看到解除注释的行的步骤,但默认情况下已经解除注释了(可能是无意间解除了注释,或者是CentOS7的设定)。
## Allows people in group wheel to run all commands
%wheel ALL=(ALL) ALL
在中文中,将以下内容进行同义转述:
切换用户 -> 使用sudo命令切换到root身份
# exit
$ ssh admin@xx.xxx.xxx.xx
$ sudo su root
We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:
#1) Respect the privacy of others.
#2) Think before you type.
#3) With great power comes great responsibility.
[sudo] password for admin:
SSH的配置
设置文件如下所示。
# vi /etc/ssh/sshd_config
禁止使用root用户登录
#PermitRootLogin yes
PermitRootLogin no
禁止使用密码登录
#PasswordAuthentication yes
PasswordAuthentication no
只需要一个选择:
【确认】未注册密钥或者authorized_keys的权限不为600。
$ ssh admin@xx.xxx.xxx.xx
Permission denied (publickey).
更改默认端口
#Port 22
Port 10022
【确认】默认端口(22)将被拒绝访问
$ ssh admin@xx.xxx.xxx.xx
ssh: connect to host xx.xxx.xxx.xx port 22: Connection refused
$ ssh admin@xx.xxx.xxx.xx -p 10022
重新启动SSH
请注意不要退出,因为更改设置文件并重新启动将导致更改生效!(不仅会导致无法进行密码登录和22号端口登录,还因为10022号端口未开放!)
# systemctl restart sshd.service
公開密钥认证
提前制作公钥可能是一个不错的选择。
苹果本地
// 鍵がない場合
$ ssh-keygen -t rsa
$ cat .ssh/id_rsa.pub
ssh-rsa .......
服务器
$ mkdir ~/.ssh
$ chmod 700 .ssh
$ cd .ssh/
$ vi authorized_keys
// ローカルの公開鍵を貼り付ける(FTPとかで送ったほうが正確だけど)
ssh-rsa .......
$ chmod 600 authorized_keys
以sudo用户身份继承PATH。
由于管理员的$PATH和sudo su root时的$PATH不匹配会很麻烦,所以我们要进行调整。
$ echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/admin/.local/bin:/home/admin/bin
$ sudo su root
# echo $PATH
/sbin:/bin:/usr/sbin:/usr/bin
# exit
$ sudo visudo
---
Defaults env_reset
Defaults env_keep = "COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR LS_COLORS"
Defaults env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE"
Defaults env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES"
Defaults env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE"
Defaults env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"
Defaults env_keep += "PATH" <-追加
// コメントアウト
#Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin
---
// 確認
$ sudo su root
# echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/admin/.local/bin:/home/admin/bin
参考来源:在使用sudo的同时继承路径 – 随心所欲地喝酒和睡觉。
防火墙设置
由于选择了CentOS7,所以我决定尝试使用防火墙而不是大家熟悉的iptables。
-
- sshのポートを22から10022とする
http(80)とhttps(443)を許可する
# cp /usr/lib/firewalld/services/ssh.xml /etc/firewalld/services/.
# vi /etc/firewalld/services/ssh.xml
---
<port protocol="tcp" port="22"/>
▼
<port protocol="tcp" port="10022"/>
---
# firewall-cmd --permanent --zone=public --add-service=http
# firewall-cmd --permanent --zone=public --add-service=https
# firewall-cmd --reload
success
// 確認
# firewall-cmd --list-all
public (default, active)
interfaces: eth0
sources:
services: dhcpv6-client http https ssh
ports:
masquerade: no
forward-ports:
icmp-blocks:
rich rules:
参考: 入门CentOS7的firewalld使用指南(附带些许systemd) – Qiita
到目前为止,操作系统(CentOS7)的安装和安全相关的初始设置已经完成。
准备 网络服务器、PHP 和数据库。
Nginx:
这次我们选择了Nginx作为Web服务器,而不是Apache。(这是我们的第一次尝试)
添加存储库
根据以下步骤,参考 Linux packages 的稳定版本的预构建软件包,添加仓库。
nginx: Linux packages 的稳定版本的预构建软件包提供了下述方法来添加仓库。
# vi /etc/yum.repos.d/nginx.repo
---
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1
---
安装和设置
编辑/etc/nginx/conf.d/default.conf文件进行配置。处于注释状态的部分是初始设置。
# yum -y install nginx
Complete!
# vi /etc/nginx/conf.d/default.conf
server {
root /var/www/html;
location / {
#root /usr/share/nginx/html;
root /var/www/html;
#index index.html index.htm;
index index.php index.html index.htm;
}
# proxy from nginx to php-fpm
location ~ \.php$ {
fastcgi_pass localhost:9000;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
include fastcgi_params;
}
}
启动和自动启动设置
# nginx -t
# systemctl start nginx
# systemctl enable nginx
文件根目錄準備完成
将admin用户添加到nginx组中。(如果没有-a选项,会覆盖并删除wheel组)
$ sudo usermod -aG nginx admin
$ exit
// 再ログインして確認
$ id
uid=1000(admin) gid=1000(admin) groups=1000(admin),10(wheel),990(nginx)
将文档根目录的权限设置为nginx。并且配置为以后创建的文件也具有相同的权限(2770)。
$ sudo chown -R nginx:nginx /var/www/html
$ sudo chmod -R 2770 /var/www/html
$ ls -lrth
drwxrws--- 2 nginx nginx 6 Apr 13 06:04 html
PHP7.1
由于标准的yum安装的PHP版本较旧(如5.6),所以我们需要添加EPEL/Remi仓库来安装PHP7.1。
添加存储库
// EPELリポジトリ
# yum -y install epel-release
Complete!
// Remiリポジトリ
# rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm
Updating / installing...
1:remi-release-7.3-2.el7.remi ################################# [100%]
安装和设置
编辑/etc/php.ini文件来进行设置。被注释掉的部分是默认状态。
// PHP7.1(php-*は使いそうなものを適当に入れてます。但し、php-fpmはnginxとの連携で必須!)
# yum -y install --enablerepo=remi-php71 php php-cli php-common php-devel php-fpm php-gd php-mbstring php-mysqlnd php-pdo php-pear php-pecl-apcu php-soap php-xml php-xmlrpc
Complete!
# php -v
PHP 7.1.8 (cli) (built: Aug 2 2017 10:45:15) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
# vi /etc/php.ini
---
;date.timezone =
date.timezone = "Asia/Tokyo"
;expose_php = On
expose_php = Off
;mbstring.language = Japanese
mbstring.language = Japanese
;mbstring.internal_encoding =
mbstring.internal_encoding = UTF-8
;mbstring.http_input =
mbstring.http_input = auto
---
PHP-FPM的配置
我要编辑与PHP7.1一起安装的PHP-FPM配置。
# vi /etc/php-fpm.d/www.conf
---
;user = apache
user = nginx
;group = apache
group = nginx
---
启动和自动启动设置
# php-fpm -t
[16-Aug-2017 18:15:04] NOTICE: configuration file /etc/php-fpm.conf test is successful
# systemctl start php-fpm
# systemctl enable php-fpm
确认
如果phpinfo()在文档根目录中能够正常显示,则表示成功。
$ cd /var/www/html
$ vi index.php
---
<?php
phpinfo();
?>
---
$ rm index.php
玛丽亚数据库
与PHP一样,如果在标准的yum中安装,版本似乎较旧,所以需要添加存储库。
添加存储库
# vi /etc/yum.repos.d/MariaDB.repo
---
# MariaDB 10.2 CentOS repository list - created 2017-08-15 04:25 UTC
# http://downloads.mariadb.org/mariadb/repositories/
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.2/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1
---
安装
# yum -y install MariaDB-server MariaDB-client
Complete!
# mysql -V
mysql Ver 15.1 Distrib 10.2.7-MariaDB, for Linux (x86_64) using readline 5.1
启动和自动启动设置
# systemctl start mariadb
# systemctl enable mariadb
在CentOS7上安装PHP7.1、h2o、MariaDB10.1和Word Press的参考。
参考:MariaDB – 设置MariaDB源 – MariaDB。
最初的设定
似乎只要用”是”回答所有基本问题,它会以令人满意的方式帮助解决。
# mysql_secure_installation
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!
In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.
Enter current password for root (enter for none):
OK, successfully used password, moving on...
Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.
Set root password? [Y/n] Y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
... Success!
By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them. This is intended only for testing, and to make the installation
go a bit smoother. You should remove them before moving into a
production environment.
Remove anonymous users? [Y/n] Y
... Success!
Normally, root should only be allowed to connect from 'localhost'. This
ensures that someone cannot guess at the root password from the network.
Disallow root login remotely? [Y/n] Y
... Success!
By default, MariaDB comes with a database named 'test' that anyone can
access. This is also intended only for testing, and should be removed
before moving into a production environment.
Remove test database and access to it? [Y/n] Y
- Dropping test database...
... Success!
- Removing privileges on test database...
... Success!
Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.
Reload privilege tables now? [Y/n] Y
... Success!
Cleaning up...
All done! If you've completed all of the above steps, your MariaDB
installation should now be secure.
Thanks for using MariaDB!
文本编码设置
# vi /etc/my.cnf.d/server.cnf
---
[mysqld]
character-set-server = utf8
---
重启
# systemctl restart mariadb
创建DB操作用户并授予权限。
在WordPress中创建一个空的数据库,并授予管理员用户权限(并设置密码)。
# mysql -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 17
Server version: 10.2.7-MariaDB MariaDB Server
MariaDB [(none)]> create database [DB Name];
Query OK, 1 row affected (0.00 sec)
MariaDB [(none)]> grant all privileges on [DB Name].* to admin@localhost identified by '[Your Password]';
Query OK, 0 rows affected (0.00 sec)
// 必要なら(反映?)
MariaDB [(none)]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
MariaDB [(none)]> quit;
Bye
准备WordPress
安装WordPress
从公式网站下载最新的WordPress
$ cd /var/www/html
$ wget http://ja.wordpress.org/latest-ja.tar.gz
--2017-08-15 14:09:10-- http://ja.wordpress.org/latest-ja.tar.gz
Resolving ja.wordpress.org (ja.wordpress.org)... 66.155.40.250, 66.155.40.249
Connecting to ja.wordpress.org (ja.wordpress.org)|66.155.40.250|:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: https://ja.wordpress.org/latest-ja.tar.gz [following]
--2017-08-15 14:09:10-- https://ja.wordpress.org/latest-ja.tar.gz
Connecting to ja.wordpress.org (ja.wordpress.org)|66.155.40.250|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 8652714 (8.3M) [application/octet-stream]
Saving to: 'latest-ja.tar.gz'
100%[========================================================>] 8,652,714 3.16MB/s in 2.6s
2017-08-15 14:09:13 (3.16 MB/s) - 'latest-ja.tar.gz' saved [8652714/8652714]
解冻·权限更改
使得可以在文档根目录直接通过wp路径进行访问。
$ tar xzvf latest-ja.tar.gz
$ mv wordpress wp
$ sudo find /var/www/html -type d -exec chmod 770 {} \;
$ sudo find /var/www/html -type f -exec chmod 660 {} \;
最初的配置
当在http://xx.xxx.xxx.xx/wp上访问时,将开始进行初始设置。

增加设置(建议)
-
- pluginインストールなどをFTP不要とする
- wp-configのパーミッション設定
$ cd /var/www/html/wp
$ sudo vi wp-config.php
---
define('FS_METHOD', 'direct');
---
$ sudo chmod 400 wp-config.php
$ ls -l
-r-------- 1 nginx nginx 4.1K Aug 16 13:05 wp-config.php
随着永久链接的更改,需要修改Nginx的配置。
这次我们将使得可以通过xx.xxx.xxx.xx/wp/YYYY/MM/DD/PostTitle这个URL进行访问。
WordPress的永久链接设置

Nginx的配置文件
server {
listen 80;
server_name xx.xxx.xxx.xx;
root /var/www/html;
index index.php index.html index.htm;
charset utf-8;
location / {
try_files $uri $uri/ @wordpress;
}
# proxy from nginx to php-fpm
location ~ \.php$ {
try_files $uri @wordpress;
fastcgi_index index.php;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
include fastcgi_params;
}
location @wordpress {
fastcgi_index index.php;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root/wp/index.php;
include fastcgi_params;
}
}
让我们使用Let’s Encrypt来支持HTTPS
我们将使用Let’s encrypt免费提供的证书来实现HTTPS支持。
但是,在此之前,需要安装Git,因为它是必需的。(顺便从源代码安装)
安装Git
# yum -y install curl-devel expat-devel gettext-devel openssl-devel zlib-devel perl-ExtUtils-MakeMaker
Complete!
# cd /usr/local/src
# wget https://www.kernel.org/pub/software/scm/git/git-2.14.1.tar.gz
[sudo] password for admin:
--2017-08-15 16:20:12-- https://www.kernel.org/pub/software/scm/git/git-2.14.1.tar.gz
# ls -l
-rw-r--r-- 1 root root 6987933 Aug 11 02:57 git-2.14.1.tar.gz
# tar xzvf git-2.14.1.tar.gz
# cd git-2.14.1/
# make prefix=/usr/local all
# make prefix=/usr/local install
// 確認(root(またはPATHが通っていない場合)だとgit version 1.8.3.1となる?)
# exit
$ git --version
git version 2.14.1
终于让我们开始加密
发行证书
$ cd /usr/local/
$ sudo git clone https://github.com/certbot/certbot
[sudo] password for admin:
Cloning into 'certbot'...
remote: Counting objects: 48175, done.
remote: Compressing objects: 100% (33/33), done.
remote: Total 48175 (delta 13), reused 17 (delta 7), pack-reused 48135
Receiving objects: 100% (48175/48175), 14.77 MiB | 3.76 MiB/s, done.
Resolving deltas: 100% (34465/34465), done.
$ cd certbot/
$ ./certbot-auto certonly --webroot --agree-tos -w /var/www/html -m hogehoge@mail.com -d hogehoge.com
确认证书
$ sudo ls -lrth /etc/letsencrypt/live/hogehoge.com
lrwxrwxrwx 1 root root 41 Aug 16 16:53 privkey.pem -> ../../archive/hogehoge/privkey1.pem
lrwxrwxrwx 1 root root 43 Aug 16 16:53 fullchain.pem -> ../../archive/hogehoge/fullchain1.pem
lrwxrwxrwx 1 root root 39 Aug 16 16:53 chain.pem -> ../../archive/hogehoge/chain1.pem
lrwxrwxrwx 1 root root 38 Aug 16 16:53 cert.pem -> ../../archive/hogehoge/cert1.pem
-rw-r--r-- 1 root root 543 Aug 16 16:53 README
随着对HTTPS的支持,需要更改Nginx的设置。
将对端口80的HTTP访问重定向到端口443的HTTPS。
server {
listen 80;
server_name hogehoge;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name hogehoge;
root /var/www/html;
index index.php index.html index.htm;
charset utf-8;
ssl_certificate /etc/letsencrypt/live/hogehoge/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/hogehoge/privkey.pem;
location / {
try_files $uri $uri/ @wordpress;
}
---略
}
我们可以根据Let’s Encrypt证书的有效期限,在cron等工具中预先设置自动更新,这样非常方便。
基本上就是以上,但还需要应用WordPress的主题、数据库备份和插件才能完成。
将PHP版本升级至7.3

// 削除
$ sudo yum remove php-*
// インストール
$ sudo yum -y install --enablerepo=remi-php73 php php-cli php-common php-devel php-fpm php-gd php-mbstring php-mysqlnd php-pdo php-pear php-pecl-apcu php-soap php-xml php-xmlrpc
PHP-FPM的设置
可能在7.1版本的操作步骤中可能遗漏了一些内容,但当更新到PHP7.3时,除了user和group之外的其他部分也需要进行编辑。
# vi /etc/php-fpm.d/www.conf
---
;listen = 127.0.0.1:9000
listen = /var/run/php-fpm/php-fpm.sock
;user = apache
user = nginx
;group = apache
group = nginx
;listen.owner = nobody
;listen.group = nobody
;listen.mode = 0660
listen.owner = nginx
listen.group = nginx
listen.mode = 0666
---
# systemctl stop php-fpm
# systemctl start php-fpm
# systemctl stop nginx
# systemctl start nginx
在忘记上述设置时出现的Nginx错误
2020/06/14 16:28:00 [crit] 28320#28320: *2 connect() to unix:/var/run/php-fpm/php-fpm.sock failed (13: Permission denied) while connecting to upstream, client: xxx.xxx.xxx.xxx, server: hogehoge.com, request: "GET /favicon.ico HTTP/1.1", upstream: "fastcgi://unix:/var/run/php-fpm/php-fpm.sock:", host: "hogehoge.com", referrer: "https://hogehoge.com/wp/"
续集
- Nginx+PHP7.1+MariaDBのphpMyAdminを構築