CentOS部署WordPress(Memcached+MariaDB+PHP+Nginx+CertBOT)

轉了一大圈博客最終還是放在WordPress上麵了,感覺不用操心把,亂七八糟的東西也懶得折騰,嗯…好像是這樣的,在此記錄一下博客搭建的過程,以便後續維護、遷移的時候也可以回顧回顧。

環境

下麵的環境均在CentOS 8上麵操作的

$ whoami
root
$ cat /etc/redhat-release 
CentOS Linux release 8.2.2004 (Core)

然後係統盡量維持在最新版

$ dnf makecache
$ dnf update -y

建議關閉SELinux和Firewalld,防火牆可以使用雲廠商自帶的

$ vim /etc/selinux/config
SELINUX=disabled
$ systemctl disable --now firewalld

最後重啟保證修改生效

$ reboot

MariaDB

MariaDB和MySQL一樣,但是MySQL新版占用內存太高了,我的1G內存小雞可能扛不太住,所以就算則MariaDB了,相對來說更輕量,資源占用率比較低。

  • 安裝MariaDB
$ dnf install mariadb-server -y
  • 開機啟動mariadb
$ systemctl enable --now mariadb
  • 初始化
$ mysql_secure_installation
......
Enter current password for root (enter for none): # 直接回車即可,因為我沒還沒有設置root密碼
......
Set root password? [Y/n] Y # 設置ROOT密碼
New password: # 輸入root密碼,我這裏輸入的是:#1nKf4D^0NGPb*Ak
Re-enter new password: 
Password updated successfully!
......
Remove anonymous users? [Y/n] Y # 移除匿名用戶
......
Disallow root login remotely? [Y/n] Y # 關閉root遠程登錄
......
Remove test database and access to it? [Y/n] Y # 移除測試數據庫
......
Reload privilege tables now? [Y/n] Y # 刷新權限表
  • 設置字符編碼為utf8

編輯配置文件我們需要修改字符集為utf8

$ vim /etc/my.cnf.d/mariadb-server.cnf
......
[mysqld]
......
# 在mysqld段增加下麵的配置
character-set-server=utf8
collation-server=utf8_unicode_ci
......

重啟服務

$ systemctl restart mariadb
  • 創建Wordpress數據庫
$ mysql -uroot -p
# 輸入root密碼
Enter password:
# 查看字符編碼
MariaDB [(none)]> \s
--------------
mysql  Ver 15.1 Distrib 10.3.17-MariaDB, for Linux (x86_64) using readline 5.1
Connection id:          8
Current database:
Current user:           root@localhost
SSL:                    Not in use
Current pager:          stdout
Using outfile:          ''
Using delimiter:        ;
Server:                 MariaDB
Server version:         10.3.17-MariaDB 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 10 sec
Threads: 7  Questions: 4  Slow queries: 0  Opens: 17  Flush tables: 1  Open tables: 11  Queries per second avg: 0.057
--------------
# 創建wp數據庫
MariaDB [(none)]> create database wp;
Query OK, 1 row affected (0.000 sec)

Memcached

為了加速我們的網站訪問,減少查詢,我們用了Memcached來做緩存服務,至於為什麽不用redis,因為Memcached足以滿足我們的服務

  • 安裝memcached
$ dnf install memcached libmemcached -y
  • 修改配置文件使隻監聽127.0.0.1
$ vim /etc/sysconfig/memcached
......
OPTIONS="-l 127.0.0.1"
......
  • 開機啟動mariadb
$ systemctl enable memcached --now

PHP

PHP這裏用的7.4版本,最好還是不要使用老版本吧

  • 安裝
$ dnf install epel-release -y
$ dnf install https://rpms.remirepo.net/enterprise/remi-release-8.rpm -y
$ dnf module reset php
$ dnf module enable php:remi-7.4 -y
$ dnf install php-pecl-memcached php-pecl-memcache php php-opcache php-gd php-curl php-mysqlnd php-zip php-mbstring php-devel php-json -y

這裏先把nginx服務安裝了

$ dnf install nginx -y
  • 修改配置

默認使用的用戶是apache,但是我們使用的是nginx,所以需要把用戶修改為nginx

$ vim /etc/php-fpm.d/www.conf
......
user = nginx
group = nginx
......
  • 修改文件授權
$ chown -R root:nginx /var/lib/php
  • 啟動
$ systemctl enable --now php-fpm

WordPress

WordPress下載解壓到指定目錄下就可以了

# 安裝wgey命令,下麵需要用到
$ dnf install wget -y
$ cd /var/www
$ wget https://wordpress.org/latest.tar.gz
$ rm -fr html
$ tar xf latest.tar.gz
$ mv wordpress html
$ rm -f latest.tar.gz
  • 設置授權
$ chown -R nginx.nginx html
  • 數據庫配置
$ cd html/
$ cp wp-config-sample.php wp-config.php
$ chown nginx.nginx wp-config.php
$ vim wp-config.php
......
define( 'DB_NAME', 'wp' );
define( 'DB_USER', 'root' );
define( 'DB_PASSWORD', '#1nKf4D^0NGPb*Ak' );
define( 'DB_HOST', 'localhost' );
......
  • SEO和Google統計(可選)

如果你的主題不提供SEO的配置,你可以編輯主題目錄下麵的header.php文件中的head標簽中添加一下代碼

vim wp-content/themes/neve/header.php
<!-- keywords and description -->
<?php if (is_home()) { 
    $description = "安生(anSheng.Me),記錄工作中可能遇到的django、djangorestframework、postgresql、docker問題,分享python教程、django教程";
    $keywords = "安生,ansheng,python,python教程,django,django教程,djangorestframework,centos,celery,postgresql,docker";
} elseif (is_single()) {
    if ($post->post_excerpt) {
        $description     = $post->post_excerpt;
    } else {
        $description = substr(strip_tags($post->post_content),0,220);
    }
    $keywords = "";
    $tags = wp_get_post_tags($post->ID);
    foreach ($tags as $tag ) {
        $keywords = $keywords . $tag->name . ",";
    }
    if (substr($keywords, -1) == ",") {
      $keywords = substr($keywords, 0, -1);
    }
} elseif (is_category()) {
    $description = category_description();
    $keywords = single_cat_title('', false);
} elseif (is_tag()) {
    $keywords = single_tag_title('', false);
    $description = "關於標簽 " . $keywords . " 的相關文章";
}
$keywords = trim(strip_tags($keywords));
$description = trim(strip_tags($description));
?>
<meta name="keywords" content="<?=$keywords?>" />
<meta name="description" content="<?=$description?>" />
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id={GOOGLE_UA_ID}"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', '{GOOGLE_UA_ID}');
</script>

Nginx

nginx在PHP部分已經安裝好了,所以直接跳過安裝進入部署

  • 部署
$ vim /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    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;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;
    include /etc/nginx/conf.d/*.conf;

    server {
        listen 80;
        server_name ansheng.me;

        root /var/www/html;
        index index.php;

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

        location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/run/php-fpm/www.sock;
            fastcgi_index index.php;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_path_info;
        }

        location = /xmlrpc.php {
            deny all;
            access_log off;
        }

        location = /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 ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
            expires max;
            log_not_found off;
        }
    }
}
  • 啟動NGINX
$ systemctl enable --now  nginx
  • 添加域名解析

我這裏使用的域名是ansheng.me,需要在域名服務商後台添加一條DNS A記錄指向到服務地址,我這裏已經添加好了。

  • 初始化wordpress

瀏覽器打開ansheng.me,一步一步初始化

選擇語言

1602997693

設置站點信息

1602997717

初始化成功之後點擊登陸,至此WP安裝已經完成了

1602997733

WordPress配置Memcached你可以安裝W3 Total Cache插件,具體配置比較簡單,這裏就不說了

CertBOT

如果你的站點並不想使用https,那麽可以直接跳過這段。

為了使用https我們需要通過使用certbot來簽發ssl整數

$ curl -O https://dl.eff.org/certbot-auto
$ mv certbot-auto /usr/local/bin/certbot-auto
$ chmod 0755 /usr/local/bin/certbot-auto
# 根據提示輸入一些信息即可
$ /usr/local/bin/certbot-auto --nginx

由於簽發的證書有效期隻有三個月,所以我們需要添加定時任務來自動續簽

$ crontab -e
0 0,12 * * * /usr/local/bin/certbot-auto renew --dry-run

下麵是使用了https的nginx完整的配置文件

$ vim /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    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;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    # 添加gzip壓縮
    gzip on;
    gzip_min_length 0;
    gzip_comp_level 9;
    gzip_types *;
    gzip_vary on;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;
    include /etc/nginx/conf.d/*.conf;

    # 隱藏nginx版本信息
    server_tokens off;

    server {
        if ($host = ansheng.me) {
            return 301 https://$host$request_uri;
        }

        listen 80;
        server_name ansheng.me;
        return 404;
    }

    server {
        listen 443 ssl http2;
        server_name ansheng.me;

        ssl_certificate /etc/letsencrypt/live/ansheng.me/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/ansheng.me/privkey.pem;
        include /etc/letsencrypt/options-ssl-nginx.conf;
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";
        ssl_session_cache shared:SSL:20m;

        root /var/www/html;
        index index.php;

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

        location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/run/php-fpm/www.sock;
            fastcgi_index index.php;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_path_info;
        }

        location = /xmlrpc.php {
            deny all;
            access_log off;
        }

        location = /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 ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
            expires max;
            log_not_found off;
        }
    }
}

當訪問http會自動跳轉到https

$ curl -I ansheng.me
HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Sun, 18 Oct 2020 04:09:15 GMT
Content-Type: text/html
Content-Length: 178
Connection: keep-alive
Location: https://ansheng.me/

https可以正常訪問

$ curl -I https://ansheng.me/
HTTP/2 200
server: nginx
date: Sun, 18 Oct 2020 04:09:23 GMT
content-type: text/html; charset=UTF-8
vary: Accept-Encoding
x-powered-by: PHP/7.4.11
link: <https://ansheng.me/wp-json/>; rel="https://api.w.org/"
strict-transport-security: max-age=31536000; includeSubDomains

當Memcached緩存配置之後,訪問幾次頁麵,然後通過telnet連接memcached查看是否生效

$ dnf install telnet -y
$ telnet localhost 11211
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
stats
......
# 關鍵數據
# 緩存訪問數
STAT cmd_get 1429813
# 緩存命中數
STAT get_hits 558390
# 緩存miss數
STAT get_misses 871423
......

相關說明:

1、VIP會員無限製任意下載,免積分。立即前往開通>>

2、下載積分可通過日常 簽到綁定郵箱 以及 積分兌換 等途徑獲得!

3、本站資源大多存儲在雲盤,如出現鏈接失效請評論反饋,如有密碼,均為:www.ipipn.com。

4、所有站內資源僅供學習交流使用。未經原版權作者許可,禁止用於任何商業環境,否則後果自負。為尊重作者版權,請購買正版作品。

5、站內資源來源於網絡公開發表文件或網友分享,如侵犯您的權益,請聯係管理員處理。

6、本站提供的源碼、模板、軟件工具等其他資源,都不包含技術服務,請大家諒解!

7、源碼、模板等資源會隨著技術、壞境的升級而存在部分問題,還請慎重選擇。

PS.源碼均收集自網絡,如有侵犯閣下權益,請發信件至: admin@ipipn.com .


源站網 » CentOS部署WordPress(Memcached+MariaDB+PHP+Nginx+CertBOT)

發表評論

讚助本站發展 維持服務器消耗

全站源碼免費下載 立刻讚助