基于LNMP的WordPress搭建与速度优化实践

817 阅读10分钟
原文链接: blog.didiyun.com

本文是滴滴云开源框架教程系列文章的一篇。

前言

WordPress是一款非常流行的内容管理系统(CMS),基于MySQL和PHP开发而成,互联网用户可以利用其快速搭建个人博客。

本文将演示:如何基于LNMP(Linux, Nginx, MySQL, PHP)快速搭建一套WordPress,并尝试优化它的访问速度。

准备

本文基于Linux发行版本Centos7.x配合流行的包管理工具yum进行演示,因此您需要准备一台Centos7.x版本的服务器并安装好yum。滴滴云DC2拥有性价比高、安全可靠和秒级计费等优势,建议您直接购买DC2来学习本教程。以下内容基于滴滴云DC2(CentOS7.4 2核CPU 4GB内存 40GBHDD存储 公网IP116.85.18.247)进行演示。

安装LNMP

1.修改yum源

PHP7.0相较于之前版本在性能上有巨大飞跃,为了提升网站性能,我们选择直接安装PHP7.0。大多数yum源只提供PHP的稳定版本(5.x),DC2上默认的yum源也是如此,因此要先修改yum源:

rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
1
2
rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
 

rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
1
2
rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
 

2.安装并启用PHP

我们选择安装PHP7.2版本以及需要的插件,包括FastCGI进程管理器PHP-FPM、数据库连接驱动MySQL Native Driver、编译缓存OpCache等:

yum -y install php72w php72w-devel php72w-cli php72w-common php72w-mysqlnd php72w-fpm php72w-opcache php72w-pecl-redis
1
2
yum -y install php72w php72w-devel php72w-cli php72w-common php72w-mysqlnd  php72w-fpm php72w-opcache php72w-pecl-redis
 

打开PHP-FPM的配置文件:

vim /etc/php-fpm.d/www.conf
1
2
vim  /etc/php-fpm.d/www.conf
 

将运行worker进程用户和group修改为nobody(最小权限):

user = nobody group = nobody
1
2
3
user = nobody
group = nobody
 

启用php-fpm:

systemctl start php-fpm.service
1
2
systemctl start php-fpm.service
 

3.安装并启用Nginx

安装Nginx:

yum -y install nginx
1
2
yum -y install nginx
 

打开Nginx配置:

vim /etc/nginx/nginx.conf
1
2
vim /etc/nginx/nginx.conf
 

将运行worker进程用户和group修改为nobody(最小权限):

user nobody;
1
2
user nobody;
 

将server部分修改为以下内容:

server { listen 80 default_server; server_name localhost; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; #默认转发规则 location / { index index.php index.html index.htm; } #.php结尾的请求转发给fpm监听端口 location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
server {
        listen       80 default_server;
        server_name  localhost;
        root         /usr/share/nginx/html;
 
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
 
        #默认转发规则
        location / {
            index index.php index.html index.htm;
        }
 
        #.php结尾的请求转发给fpm监听端口
        location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
 
        error_page 404 /404.html;
            location = /40x.html {
        }
 
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
 
 

启用Nginx:

systemctl start nginx.service
1
2
systemctl start nginx.service
 

4.安装并启用MariaDB

安装Mariadb:

yum -y install mariadb-server mariadb mariadb-devel
1
2
yum -y install mariadb-server mariadb mariadb-devel
 

mysql_secure_installation
1
2
mysql_secure_installation
 

修改Mariadb数据库root用户密码,删除匿名用户、测试数据库,重载授权表:

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY! Set root password? [Y/n] y New password: Re-enter new password: Password updated successfully! Reloading privilege tables.. ... Success! 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 - Dropping test database... ... Success! - Removing privileges on test database... ... Success! Reload privilege tables now? [Y/n] y ... Success!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!
 
Set root password? [Y/n] y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
... Success!
 
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
- Dropping test database...
... Success!
- Removing privileges on test database...
... Success!
 
Reload privilege tables now? [Y/n] y
... Success!
 

运行Mariadb:

systemctl start mariadb.service
1
2
systemctl start mariadb.service
 

以root账户连接Mariadb:

mysql -uroot -p
1
2
mysql -uroot -p
 

创建WordPress需要的数据库your_domain、账户wordpressuser和密码password:

mysql> CREATE DATABASE your_domain DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
1
2
mysql> CREATE DATABASE your_domain DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
 

mysql> GRANT ALL ON your_domain.* TO 'wordpressuser'@'localhost' IDENTIFIED BY 'password';
1
2
mysql> GRANT ALL ON your_domain.* TO 'wordpressuser'@'localhost' IDENTIFIED BY 'password';
 

mysql> FLUSH PRIVILEGES; mysql> EXIT;
1
2
3
mysql> FLUSH PRIVILEGES;
mysql> EXIT;
 

5.验证LNMP

写一个简单的php脚本验证安装是否成功:

vim /usr/share/nginx/html/index.php
1
2
vim /usr/share/nginx/html/index.php
 

写入以下内容:

<?php $conn = mysqli_connect("127.0.0.1", "wordpressuser", "password"); if ($conn) { echo "succ"; } mysqli_close(); echo phpinfo();
1
2
3
4
5
6
7
8
<?php
    $conn = mysqli_connect("127.0.0.1", "wordpressuser", "password");
    if ($conn) {
        echo "succ";
    }
    mysqli_close();
    echo phpinfo();
 

在浏览器中输入http://your_ip/index.php(your_ip为您服务器的公网ip),如果展示succ以及php配置信息说明配置成功:

在这里插入图片描述

如果报错请检查您的以上各项配置是否正确,或者通过cli直接运行index.php进行调试:

/usr/bin/php /usr/share/nginx/html/index.php
1
2
/usr/bin/php /usr/share/nginx/html/index.php
 

安装WordPress

1.下载WordPress

cd /usr/share/nginx/html/
1
2
cd /usr/share/nginx/html/
 

curl -LO https://wordpress.org/latest.tar.gz
1
2
curl -LO https://wordpress.org/latest.tar.gz
 

tar xzvf latest.tar.gz
1
2
tar xzvf latest.tar.gz
 

为了保证Nginx和fpm可访问以及安全性,修改目录所属用户组为www,对nobody用户仅保留可读权限:

useradd www
1
2
useradd www
 

chown -R www:www /usr/share/nginx/html/
1
2
chown -R www:www /usr/share/nginx/html/
 

2.配置WordPress

cp wordpress/wp-config-sample.php wordpress/wp-config.php
1
2
cp wordpress/wp-config-sample.php wordpress/wp-config.php
 

vim wordpress/wp-config.php
1
2
vim wordpress/wp-config.php
 

修改数据库访问内容:

define('DB_NAME', 'your_domain'); /** MySQL database username */ define('DB_USER', 'wordpressuser'); /** MySQL database password */ define('DB_PASSWORD', 'password');
1
2
3
4
5
6
define('DB_NAME', 'your_domain');
/** MySQL database username */
define('DB_USER', 'wordpressuser');
/** MySQL database password */
define('DB_PASSWORD', 'password');
 

3.完成安装并访问

浏览器打开网址:

http://your_ip/wordpress
1
2
http://your_ip/wordpress
 

打开WordPress安装欢迎页,设置用户名密码和邮箱并登陆:

在这里插入图片描述

再次在浏览器中输入地址:

http://your_ip/wordpress
1
2
http://your_ip/wordpress
 

你会看到博客的首页,大功告成!

在这里插入图片描述

优化访问速度

强制刷新博客首页,我们会发现有明显的延迟感,这是因为你的网站缺乏足够的优化。SmartBear研究表明,Amazon加载时间每延长1秒一年就会减少16亿美元的营收,可见网站响应快是多么重要。接下来我们会从网络传输、服务器响应以及页面加载等几个层面介绍如何对网站进行优化。

1.检测当前网站状况

GTmetrix是一个免费的网站加载检测工具,并根据检测结果提供优化建议,在浏览器输入https://gtmetrix.com/开始检测:

在这里插入图片描述

检测结果显示页面加载用时2.8秒、响应内容448KB,并建议开启gzip压缩、更换css版本以及推迟解析js脚本等等:

在这里插入图片描述

2.降低网络传输时间

Nginx开启gzip压缩可以将服务器响应内容(尤其是文本内容)进行压缩后传输给浏览器,显著降低响应内容的大小,降低传输时间,在nginx.conf中server部分增加以下内容:

gzip on; gzip_min_length 1k; # gzip 压缩级别,1-10,数字越大压缩的越好,也越占用CPU时间,后面会有详细说明 gzip_comp_level 5; # 进行压缩的文件类型。javascript有多种形式。其中的值可以在 mime.types 文件中找到。 gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png font/ttf font/otf image/svg+xml; # 是否在http header中添加Vary: Accept-Encoding,建议开启 gzip_vary on; # 禁用IE 6 gzip gzip_disable "MSIE [1-6]\.";
1
2
3
4
5
6
7
8
9
10
11
gzip on;
gzip_min_length 1k;
# gzip 压缩级别,1-10,数字越大压缩的越好,也越占用CPU时间,后面会有详细说明
gzip_comp_level 5;
# 进行压缩的文件类型。javascript有多种形式。其中的值可以在 mime.types 文件中找到。
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png font/ttf font/otf image/svg+xml;
# 是否在http header中添加Vary: Accept-Encoding,建议开启
gzip_vary on;
# 禁用IE 6 gzip
gzip_disable "MSIE [1-6]\.";
 

同时开启Nginx缓存,如果请求命中缓存,Nginx会直接进行响应:

location ~* ^.+\.(eot|ttf|otf|woff|svg)$ { access_log off; expires max; } location ~* ^.+\.(ico|gif|jpg|jpeg|png)$ { access_log off; expires 30d; } location ~* ^.+\.(css|js|txt|xml|swf|wav)$ { access_log off; expires 2d; } location ~* ^.+\.(html|htm)$ { expires 1h; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
location ~* ^.+\.(eot|ttf|otf|woff|svg)$ {
    access_log   off;
    expires max;
}
location ~* ^.+\.(ico|gif|jpg|jpeg|png)$ {
    access_log   off;
    expires      30d;
}                  
location ~* ^.+\.(css|js|txt|xml|swf|wav)$ {
    access_log   off;
    expires      2d;
}                
location ~* ^.+\.(html|htm)$ {
    expires      1h;
}
 

缓存时间可以根据情况自行设定

3.降低服务器响应时间

Opcache可以将PHP代码预编译生成脚本文件 Opcode并缓存在内存中,避免执行PHP脚本时再次进行编译,从而加速PHP的执行。打开配置Opcache配置文件:

vim /etc/php.d/opcache.ini
1
2
vim /etc/php.d/opcache.ini
 

修改以下参数为对应值:

zend_extension=opcache.so opcache.enable=1 opcache.enable_cli=1
1
2
3
4
zend_extension=opcache.so
opcache.enable=1
opcache.enable_cli=1
 

另外,可以通过设置缓存来减少对数据库的访问,从而降低访问时间。Redis Object Cache插件通过重写object-cache.php文件,把对象缓存到Redis中,来帮助我们达成目的。首先在WordPress控制台安装并激活插件:

在这里插入图片描述
替换object-cache.php文件:

cp wordpress/wp-content/plugins/redis-cache/includes/object-cache.php wordpress/wp-content/object-cache.php
1
2
cp wordpress/wp-content/plugins/redis-cache/includes/object-cache.php wordpress/wp-content/object-cache.php
 

其次安装并启用Redis:

yum install redis
1
2
yum install redis
 

systemctl start redis.service
1
2
systemctl start redis.service
 

刷新网站,连接Redis默认端口进行验证(插件也默认连接此端口):

redis-cli -h 127.0.0.1 -p 6379
1
2
redis-cli -h 127.0.0.1 -p 6379
 

如果有缓存数据说明插件生效:

127.0.0.1:6379> KEYS *
1
2
127.0.0.1:6379> KEYS *
 

4.延迟加载js文件

我们打开网站时,浏览器会从上到下加载html代码进行渲染。通过推迟解析JavaScript,可以更快的渲染。我们对主题添加一段代码(您也可以通过安装插件完成),来达到这一目的。

打开你的WordPress网站主题下的functions.php文件,比如本文使用的主题是twentyseventeen:

vim wp-content/themes/twentyseventeen/functions.php
1
2
vim wp-content/themes/twentyseventeen/functions.php
 

在文件底部,增加以下代码:

function defer_parsing_of_js ( $url ) { if ( FALSE === strpos( $url, '.js' ) ) { return $url; } if ( strpos( $url, 'jquery.js' ) ) { return $url; } return "$url' defer "; } add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 );
1
2
3
4
5
6
7
8
9
10
11
function defer_parsing_of_js ( $url ) {
    if ( FALSE === strpos( $url, '.js' ) ) {
        return $url;
    }
    if ( strpos( $url, 'jquery.js' ) ) {
        return $url;
    }
    return "$url' defer ";
}
add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 );
 

5.禁用Google字体

打开浏览器调试窗口,刷新网页查看请求:

在这里插入图片描述
可以看到有几个访问fonts.gstatic.com带.woff2后缀的请求,耗时均超过1s,严重影响页面加载速度。这是WordPress在加载外部谷歌字体,我们可以安装插件Disable Google Fonts来禁用这一外链:
在这里插入图片描述
再次刷新网页查看请求,可以看到实际页面加载时间已经从2s降到1s以下
在这里插入图片描述

5.对比优化结果

最后再次打开GTmetrix,重新进行检测对比(由于GTmetrix默认从加拿大节点发起访问,网路较长,可能有一些不稳定因素,可以多试几次)优化结果:

在这里插入图片描述

可以看到网站加载时间、响应内容等各项都已经得到明显优化

总结

基于LNMP搭建WordPress过程看似非常简单,但其中涉及的知识面很广泛。限于篇幅,本文对其中大多内容进行简述。不过,理解其中的各个过程(LNMP、网络以及安全)并进行深度学习,对各位Web开发者技能提升非常有益,与诸位共勉。

引用

nginx.org/en/docs/htt…

www.wpbeginner.com/wordpress-p…

juejin.cn/post/684490…

本文作者:于双羽