Ubuntu18.04针对LNMP和Wordpress的优化【不断更新中】

|

Linode上部署wordpress的时候,遇到了一些需要优化的地方,就在这里做一下记录。

一、Linux系统优化

ulimit -n # 查看文件打开句柄数系统默认值
sudo vi /etc/security/limits.conf
* hard nofile 65535
* soft nofile 65535
root hard nofile 65535

sudo vi /etc/sysctl.conf
fs.file-max = 888888 # 这里要大于limits的数字
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_keepalive_time = 15
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_max_tw_buckets = 5000
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.tcp_rmem = 4096 32768 262144
net.ipv4.tcp_wmem = 4096 32768 262144
net.ipv4.tcp_max_orphans = 262144 
net.core.netdev_max_backlog = 262144
net.core.rmem_default = 262144
net.core.wmem_default = 262144
net.core.rmem_max = 2097152
net.core.wmem_max = 2097152
net.core.somaxconn = 262144 
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog=262144
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
sudo sysctl -p

sudo vi /etc/fstab
errors=remount-ro 0 1 替换为 errors=remount-ro,noatime,nodiratime,usrjquota=quota.user,grpjquota=quota.group,jqfmt=vfsv0 0 1
sudo mount -o remount /

二、Nginx优化

下面是huwencai.com的nginx配置文件:

sudo vi /etc/nginx/nginx.conf
user www-data; #配置worker进程所属用户,用户组
worker_processes 1; #配置worker进程数量,为避免cpu切换损耗,配置和系统内核数一样即可,或者auto
worker_cpu_affinity auto; #配置cpu亲和,auto 代表自动绑定
worker_rlimit_nofile 40960; #nginx进程打开文件描述符数目,此值覆盖ulimit -n的值。
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
worker_connections 10240; # 每个woker的最多连接数目
multi_accept on; # 启用收到一个新连接通知后接受尽可能多的连接
accept_mutex on; # 设置为on worker进程轮流接受新链接,官方推荐设置为off.高负载的情况下设置为on.
use epoll; # 设置用于复用客户端线程的轮询方法
}

http {

##
# Basic Settings
##

sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 15; #为了尽快释放连接,可以设置小点. 15 至 30
types_hash_max_size 2048;
server_tokens off; #隐藏响应头中的有关操作系统和web server(Nginx)版本号的信息
autoindex off;

client_header_timeout 30;
client_body_timeout 30;
send_timeout 60;
proxy_send_timeout 300;
reset_timedout_connection on;

client_body_buffer_size 16K;
client_header_buffer_size 1K;
client_max_body_size 20m; #设置nginx能够上传的最大文件

fastcgi_hide_header X-Powered-By;
proxy_hide_header X-Powered-By;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;

# 安全相关 header
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Feature-Policy "autoplay 'none'; camera 'none'" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

##
# File Cache Settings
##

open_file_cache max=5000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;

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

##
# SSL Settings
##

ssl_ciphers HIGH:!aNULL:!MD5;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;

##
# Logging Settings
##

access_log /var/log/nginx/access.log main buffer=16k;
error_log /var/log/nginx/error.log main buffer=16k;

##
# Gzip Settings
##

gzip on;

gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

##
# Nginx FastCGI Cache
##

fastcgi_cache_path /var/cache/nginx/ levels=1:2 keys_zone=cachezone:10m max_size=2g inactive=60m;
fastcgi_cache_key $scheme$request_method$host$request_uri;
fastcgi_cache_lock on;
fastcgi_cache_revalidate on;
fastcgi_cache_background_update on;
fastcgi_cache_use_stale error timeout invalid_header updating http_500;
fastcgi_cache_valid any 60m;
fastcgi_pass_header Set-Cookie;
fastcgi_pass_header Cookie;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

##
# Virtual Host Configs
##

include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}

记得创建缓存目录/var/cache/nginx/ 并授权给www-data。
下面是huwencai.com的虚拟机配置文件:

sudo vi /etc/nginx/sites-available/huwencai.com
# Redirect HTTP -> HTTPS
server {
    listen 80;
    server_name www.huwencai.com huwencai.com;

    include snippets/letsencrypt.conf;
    return 301 https://huwencai.com$request_uri;
}

# Redirect WWW -> NON WWW
server {
    listen 443 ssl http2;
    server_name www.huwencai.com;

    ssl_certificate /etc/letsencrypt/live/huwencai.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/huwencai.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/huwencai.com/chain.pem;
    include snippets/ssl.conf;

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

limit_req_zone $binary_remote_addr zone=WPRATELIMIT:10m rate=2r/s;
server {
    listen 443 ssl http2;
    server_name huwencai.com;

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

    # SSL parameters
    ssl_certificate /etc/letsencrypt/live/huwencai.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/huwencai.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/huwencai.com/chain.pem;
    include snippets/ssl.conf;
    include snippets/letsencrypt.conf;

    # log files
    access_log /var/log/nginx/huwencai.com.access.log main buffer=16k;
    error_log /var/log/nginx/huwencai.com.error.log main buffer=16k;

    location = /favicon.ico {
        try_files $uri =204;
        expires max;
        log_not_found off;
        access_log off;
    }

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

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

    # 禁止访问 /wp-content/ 目录的 php 格式文件 (包含子目录)
    location ~* ^/wp-content/.*.(php|phps)$ {
        deny all;
        access_log off;
        log_not_found off;
    }

   # 禁止访问 /wp-content/ 目录的以下文件格式 (包含子目录)
    location ~* ^/wp-content/.*.(txt|md|exe)$ {
        return 403;
        access_log off;
        log_not_found off;
    }

    # 允许内部分 wp-includes 目录的 .php 文件
    location ~* ^/wp-includes/.*\.(php|phps)$ {
        internal;
    }

    # 禁止访问 wp-config.php 文件
    location = /wp-config.php {
        deny all;
        access_log off;
        log_not_found off;
    }

    location ~* /xmlrpc.php$ {
        allow 127.0.0.1;
        deny all;
        access_log off;
        log_not_found off;
        return 444;
    }

    location ~* ^/wp-admin/(setup-config|install)\.php$ {
        deny all;
        access_log off;
        log_not_found off;
    }

    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }

    if ($request_uri ~* "^.+(readme|license)\.(txt|html)$") {
        return 403;
    }

    location /wp-content/uploads/ {
        location ~ \.php$ {
                deny all;
        }
    }

    location ~ \wp-login.php$ {
        limit_req zone=WPRATELIMIT;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

        set $skip_cache 0;
        # POST requests and url's with a query string should always skip cache
        if ($request_method = POST) {
               set $skip_cache 1;
        }
        if ($query_string != "") {
               set $skip_cache 1;
        }
        # Don't cache url's containing the following segments
        if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") {
               set $skip_cache 1;
        }
        # Don't use the cache for logged in users or recent commenters
        if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
               set $skip_cache 1;
        }
        # (for some reason, add_header fails if included in prior if-block)
        if ($skip_cache = 1) {
               add_header Set-Cookie "_mcnc=1; Max-Age=2; Path=/";
               add_header X-Microcachable "0";
        }
        # Bypass cache if no-cache cookie is set
        if ($http_cookie ~* "_mcnc") {
               set $skip_cache 1;
        }

        fastcgi_cache_bypass $skip_cache;
        fastcgi_no_cache $skip_cache;
        fastcgi_cache cachezone;
        include fastcgi_params;
        fastcgi_buffer_size 128k;
        fastcgi_connect_timeout 60s;
        fastcgi_send_timeout 60s;
        fastcgi_read_timeout 60s;
        fastcgi_buffers 256 16k;
        fastcgi_busy_buffers_size 256k;
        fastcgi_temp_file_write_size 256k;
    }

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

}

三、PHP优化

sudo vi /etc/php/7.2/fpm/pool.d/www.conf
listen.owner = www-data
listen.group = www-data
listen.mode = 0660 #降低网络开销,将TCP更换为UNIX的socket.
pm = dynamic #指定进程管理方式,有3种可供选择:static、dynamic和ondemand。
pm.max_children = 15 #static模式下创建的子进程数或dynamic模式下同一时刻允许最大的php-fpm子进程数量。
pm.start_servers = 6 #动态方式下的起始php-fpm进程数量。
pm.min_spare_servers = 6 #动态方式下服务器空闲时最小php-fpm进程数量。
pm.max_spare_servers = 12 #动态方式下服务器空闲时最大php-fpm进程数量。
pm.max_requests = 1000 #php-fpm子进程能处理的最大请求数。
pm.process_idle_timeout = 10s
request_terminate_timeout = 100 #将执行时间太长的进程直接终止
request_slowlog_timeout = 2
slowlog = var/log/slow.log #日志文件
#这里根据实际情况设置

sudo vi /etc/php/7.2/fpm/php.ini
expose_php = Off #隐藏PHP版本号
session.cache_limiter = none #解决缓存优化时session问题
opcache.enable=1 #开启opcache缓存
opcache.enable_cli=1
opcache.memory_consumption=128 #opcache可用内存128M
opcache.max_accelerated_files=3000
opcache.revalidate_freq = 100
max_execution_time = 3000 #设置php最大执行时间
memory_limit = 256M #设置php的内存限制建议主机内存的1/4
upload_max_filesize = 20M #设置php上传文件大小
post_max_size = 20M

四、MySQL优化

MySQL目前没有做优化,如果想优化建议用单独数据库服务器。
下面是我在网上找的别人的优化方案。修改mysqld.cnf

sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf
key_buffer_size		= 256k
max_allowed_packet	= 1M
thread_stack		= 64K
thread_cache_size       = 8
max_connections        = 20
performance_schema_max_table_instances = 200
table_definition_cache = 200
table_open_cache       = 64
thread_concurrency     = 8
query_cache_limit	= 256k
query_cache_size        = 4M
expire_logs_days	= 3
max_binlog_size   = 10M
innodb_buffer_pool_size = 128M
innodb_log_file_size = 10M
innodb_buffer_pool_instances = 2
innodb_io_capacity = 1000
sort_buffer_size = 256K
read_buffer_size = 256K
read_rnd_buffer_size = 256K
net_buffer_length = 2K

五、使用Redis缓存

Redis可以作为数据库的缓存,减少数据库读写的次数

sudo apt install redis-server
sudo systemctl status redis-server
在wordpress里寻找Redis Object Cache插件
把wp-content/plugins/redis-cache/includes/object-cache.php拷贝到wp-content/object-cache.php

六、Wordpress本身优化

修改wp-config.php文件在define(‘DB_COLLATE’, ”);下面添加下面两个
define( ‘WP_MEMORY_LIMIT’, ‘256M’ ); //这里设置wordpress能够用内存大小
define( ‘WP_POST_REVISIONS’, 3 ); //这里控制版本数量,设置成false就是关闭版本控制

图片格式我建议用webp格式,压缩率高,图片损失小。下面是让wordpress支持webp格式图片并在媒体库可预览的代码,加入主题的functions.php的最低部:

//下方一段为webp格式图片支持代码
function webp_filter_mime_types( $array ) {
  $array['webp'] = 'image/webp';
  return $array;
}
add_filter( 'mime_types', 'webp_filter_mime_types', 10, 1 );
//下方为webp格式图片在媒体库预览图像支持代码
function webp_file_is_displayable_image($result, $path) {
  $info = @getimagesize( $path );
  if($info['mime'] == 'image/webp') {
    $result = true;
  }
  return $result;
}
add_filter( 'file_is_displayable_image', 'webp_file_is_displayable_image', 10, 2 );

类似文章

发表回复

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