在VPS上搭建WordPress网站并通过Redis Cache和Fastcgi Cache提速

|

在用过很多家Wordpress主机后,发现Wordpress主机虽然方便,但是每家都会有各自的小问题。有些可能无所谓,有些就很重要。再加上本人喜欢折腾,就又重新回到使用VPS来搭建WordPress网站。

废话不多说,如何购买VPS以及购买后的初始化这里我就不再重复了,大家可以看我以前的文章。另外我使用的系统是Ubuntu 20.04,大家在部署的时候不用选错了,避免不必要的麻烦。

1. SSH进入系统,更新系统并建立一个非root的sudo用户

apt update -y
apt upgrade -y
apt autoremove -y
echo "huwencai.com" > /etc/hostname  #这里修改主机名,可以根据需要来弄
hostname -F /etc/hostname
adduser username
adduser username sudo
su - username

2. 安装设置防火墙

sudo apt install ufw
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https
sudo ufw show added
sudo ufw enable
sudo ufw status verbose

3. 安装Fail2ban

sudo apt install fail2ban
sudo service fail2ban start

4. 安装配置Nginx

sudo apt install nginx -y

运行下面两个命令并记录下来:

grep processor /proc/cpuinfo | wc -l
ulimit -n

删除Nginx的default设置,并设置IP访问报444错误:

sudo rm /etc/nginx/sites-available/default
sudo rm /etc/nginx/sites-enabled/default

修改/etc/nginx/nginx.conf文件为一下内容:

user www-data;
worker_processes 4;  #这里是CPU核心数
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
	worker_connections 768;  #这里是ulimit -n获取的数字
	multi_accept on;
}

http {
	# Basic Settings
	sendfile on;
	tcp_nopush on;
	tcp_nodelay on;
	keepalive_timeout 15;
	client_body_timeout 30;
	client_header_timeout 30;
	send_timeout 30;
	types_hash_max_size 2048;
	client_max_body_size 100m;

	# server_names_hash_bucket_size 64;
	# server_name_in_redirect off;

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

	# SSL Settings
	ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
	ssl_prefer_server_ciphers on;

	fastcgi_buffers 16 16k;
	fastcgi_buffer_size 32k;

	# Logging Settings
	access_log /var/log/nginx/access.log;
	error_log /var/log/nginx/error.log;

	# Gzip Settings
	gzip on;
	gzip_disable "msie6";
	gzip_vary on;
	gzip_proxied any;
	gzip_comp_level 5;
	gzip_http_version 1.1;
	gzip_min_length 256;
	gzip_types
		application/atom+xml
		application/javascript
		application/json
		application/ld+json
		application/manifest+json
		application/rss+xml
		application/vnd.geo+json
		application/vnd.ms-fontobject
		application/x-font-ttf
		application/x-web-app-manifest+json
		application/xhtml+xml
		application/xml
		font/opentype
		image/bmp
		image/svg+xml
		image/x-icon
		text/cache-manifest
		text/css
		text/plain
		text/vcard
		text/vnd.rim.location.xloc
		text/vtt
		text/x-component
		text/x-cross-domain-policy;

	# Virtual Host Configs
	include /etc/nginx/conf.d/*.conf;
	include /etc/nginx/sites-enabled/*;

	server {
		listen 80 default_server;
		listen [::]:80 default_server;
		server_name _;
		return 444;
	}

}


#mail {
#       # See sample authentication script at:
#       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
# 
#       # auth_http localhost/auth.php;
#       # pop3_capabilities "TOP" "USER";
#       # imap_capabilities "IMAP4rev1" "UIDPLUS";
# 
#       server {
#               listen     localhost:110;
#               protocol   pop3;
#               proxy      on;
#       }
# 
#       server {
#               listen     localhost:143;
#               protocol   imap;
#               proxy      on;
#       }
#}

修改/etc/nginx/fastcgi_params文件为一下内容:

fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;  #添加这一行
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REQUEST_SCHEME     $scheme;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

检测一下Nginx配置文件是否正确并重启Nginx:

sudo nginx -t
sudo service nginx restart

5. 安装配置PHP

sudo apt install php-fpm php-common php-mysql \
php-xml php-xmlrpc php-curl php-gd \
php-imagick php-cli php-dev php-imap \
php-mbstring php-opcache php-redis \
php-soap php-zip -y

修改/etc/php/7.4/fpm/php.ini以下选项:

upload_max_filesize = 64M
post_max_size = 64M

检查PHP配置文件并重启PHP

sudo php-fpm7.4 -t
sudo service php7.4-fpm restart

6. 安装WP-CLI

cd ~/
curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
php wp-cli.phar --info
chmod +x wp-cli.phar
sudo mv wp-cli.phar /usr/local/bin/wp

7. 安装配置MariaDB

sudo apt install mariadb-server -y
sudo mysql_secure_installation

为WordPress创建数据库

sudo mysql -u root -p
CREATE DATABASE huwencai_com CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
CREATE USER 'huwencai'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON huwencai_com.* TO 'huwencai'@'localhost';
FLUSH PRIVILEGES;
exit;

8. 安装Certbot并创建SSL证书

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx certonly -d huwencai.com -d www.huwencai.com
sudo certbot renew --dry-run

9.创建网站目录及Nginx配置文件,并用WP-CLI安装WordPress

sudo chown -R www-data: /var/www/
cd /var/www
sudo -u www-data mkdir -p huwencai.com/logs huwencai.com/public huwencai.com/cache
chmod -R 755 huwencai.com
cd /var/www/huwencai.com/public
sudo -u www-data wp core download

创建/etc/nginx/sites-available/huwencai.com文件:

fastcgi_cache_path /var/www/huwencai.com/cache levels=1:2 keys_zone=huwencai.com:100m inactive=60m;

server {
	listen 443 ssl http2;
	listen [::]:443 ssl http2;

	server_name www.huwencai.com;
	
	root /var/www/huwencai.com/public/;
	index index.php;

	ssl_certificate /etc/letsencrypt/live/huwencai.com/fullchain.pem;
	ssl_certificate_key /etc/letsencrypt/live/huwencai.com/privkey.pem;

	access_log /var/www/huwencai.com/logs/access.log;
	error_log /var/www/huwencai.com/logs/error.log;

	location ~* /\.(?!well-known\/) {
		deny all;
	}

	location ~\.(ini|log|conf)$ {
		deny all;
	}

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

	server_tokens off;

	add_header X-Frame-Options "SAMEORIGIN" always;

	add_header X-Content-Type-Options "nosniff" always;

	add_header X-Xss-Protection "1; mode=block" always;

	# add_header Content-Security-Policy "default-src 'self' https: data: 'unsafe-inline' 'unsafe-eval';" always;

	location ~* \.(?:manifest|appcache|html?|xml|json)$ {
		expires 0;
	}

	location ~* \.(?:rss|atom)$ {
		expires 1h;
	}

	location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|mp4|ogg|ogv|webm|htc)$ {
		expires 1y;
		access_log off;
	}

	location ~* \.svgz$ {
		expires 1y;
		access_log off;
		gzip off;
	}

	location ~* \.(?:css|js)$ {
		expires 1y;
		access_log off;
	}

	location ~* \.(?:ttf|ttc|otf|eot|woff|woff2)$ {
		expires 1y;
		access_log off;
		add_header Access-Control-Allow-Origin *;
	}

	location = /favicon.ico {
	  try_files /favicon.ico @empty;
	  access_log off;
	  log_not_found off;
	  expires max;
	}

	location = /robots.txt {
	    allow all;
	    log_not_found off;
	    access_log off;
	    try_files $uri /index.php?$args;
	}

	fastcgi_cache_key "$scheme$request_method$host$request_uri";

	fastcgi_cache_use_stale error timeout updating invalid_header http_500;

	fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

	add_header Fastcgi-Cache $upstream_cache_status;

	set $skip_cache 0;

	if ($request_method = POST) {
		set $skip_cache 1;
	}

	if ($query_string != "") {
		set $skip_cache 1;
	}

	if ($request_uri ~* "/wp-admin/|/wp-json/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml|/cart/|/checkout/|/my-account/") {
		set $skip_cache 1;
	}

	if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in|edd_items_in_cart|woocommerce_items_in_cart") {
		set $skip_cache 1;
	}

	# ssl_protocols TLSv1.2;
	# ssl_ciphers EECDH+CHACHA20:EECDH+AES;
	# ssl_ecdh_curve X25519:prime256v1:secp521r1:secp384r1;
	# ssl_prefer_server_ciphers on;
	ssl_session_cache shared:SSL:10m;
	ssl_session_timeout 1h;

	add_header Strict-Transport-Security "max-age=31536000;";
	# add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;";

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

	location ~ \.php$ {
		try_files $uri =404;
		include fastcgi_params;
		fastcgi_pass unix:/run/php/php7.4-fpm.sock;
		fastcgi_cache_bypass $skip_cache;
		fastcgi_no_cache $skip_cache;
		fastcgi_cache huwencai.com;
		fastcgi_cache_valid 60m;
	}
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    server_name huwencai.com;

    ssl_certificate /etc/letsencrypt/live/huwencai.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/huwencai.com/privkey.pem;

    return 301 https://www.huwencai.com$request_uri;
}

server {
    listen 80;
    listen [::]:80;

    server_name huwencai.com www.huwencai.com;

    return 301 https://www.huwencai.com$request_uri;
}
sudo ln -s /etc/nginx/sites-available/huwencai.com /etc/nginx/sites-enabled/huwencai.com
sudo nginx -t
sudo service nginx reload

访问huwencai.com并安装设置WordPress

10. 安装Redis以及WordPress安装必要的插件

sudo apt install redis-server
sudo service php7.4-fpm restart

在WordPress里安装Redis Object Cache和Nginx Cache这两个插件
Nginx Cache里设置的位置为/var/www/huwencai.com/cache

类似文章

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注