上一篇 下一篇 分享链接 返回 返回顶部

Debian 网站提速实战:Nginx、PHP、Redis 与数据库优化源码整理

发布人:慈云数据-客服中心 发布时间:11小时前 阅读量:4

Debian 如何提高网站速度|附源码

网站速度不仅影响用户体验,也直接影响搜索引擎排名、转化率和服务器成本。对于使用 Debian 作为服务器系统的网站来说,性能优化并不只是“换更好的机器”,更多时候可以通过合理配置系统、Web 服务、缓存、数据库、静态资源和安全策略,让网站在相同硬件条件下获得明显提升。

本文将以 Debian 11/12 为主要环境,围绕 Nginx、PHP-FPM、MariaDB/MySQL、Redis、系统内核参数、静态资源压缩、浏览器缓存、HTTP/2、Gzip/Brotli、页面缓存 等方面,系统介绍如何提高网站访问速度,并附带可直接参考的配置源码。

适用场景:WordPress、ThinkPHP、Laravel、Typecho、Discuz、自研 PHP 网站、静态站点、前后端分离项目等。


一、网站速度慢的常见原因

在开始优化之前,必须先明白网站为什么会慢。很多人看到网站访问慢,第一反应就是升级服务器,但实际上,速度慢通常由以下几类问题造成:

  1. 服务器配置不合理

    • Nginx worker 数量太少
    • PHP-FPM 进程数过低或过高
    • 数据库连接数、缓存参数不合理
  2. 没有启用缓存

    • 每次请求都查询数据库
    • 每次访问都动态生成页面
    • 静态资源没有设置浏览器缓存
  3. 静态资源过大

    • 图片未压缩
    • CSS、JS 文件没有压缩
    • 没有启用 Gzip 或 Brotli
  4. 数据库查询效率低

    • 没有索引
    • 慢查询过多
    • 数据库缓冲区太小
  5. 网络层优化不足

    • 未启用 HTTP/2
    • TLS 配置不合理
    • 没有使用 CDN
  6. 程序代码效率问题

    • 重复查询数据库
    • 未使用对象缓存
    • 不必要的外部请求太多

因此,优化网站速度应该从多个层面入手,而不是只调一个参数。


二、更新 Debian 系统与基础软件

首先,确保 Debian 系统和基础软件包是最新的。新版本通常修复了安全问题,也可能带来性能提升。

sudo apt update
sudo apt upgrade -y
sudo apt autoremove -y

安装常用工具:

sudo apt install -y curl wget vim htop unzip git net-tools lsof cron

建议安装 htop 用于观察 CPU、内存和进程状态:

htop

如果你的网站已经在运行,可以通过下面命令查看当前服务器资源使用情况:

free -h
df -h
uptime

查看端口监听情况:

ss -tunlp

这些基础信息可以帮助你判断瓶颈是在 CPU、内存、磁盘还是网络。


三、优化 Nginx 配置

Nginx 是 Debian 上非常常见的 Web 服务器。相比 Apache,Nginx 在高并发场景下通常更加轻量。合理配置 Nginx,可以显著提升网站响应速度。

1. 安装 Nginx

sudo apt install -y nginx
sudo systemctl enable nginx
sudo systemctl start nginx

查看 Nginx 状态:

sudo systemctl status nginx

2. 优化 nginx.conf

编辑主配置文件:

sudo vim /etc/nginx/nginx.conf

可以参考以下配置:

user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 4096;
    multi_accept on;
    use epoll;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    types_hash_max_size 2048;
    server_tokens off;

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

    keepalive_timeout 65;
    keepalive_requests 1000;

    client_max_body_size 50m;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log warn;

    gzip on;
    gzip_comp_level 5;
    gzip_min_length 1024;
    gzip_vary on;
    gzip_proxied any;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/javascript
        application/json
        application/xml
        application/rss+xml
        image/svg+xml;

    open_file_cache max=10000 inactive=60s;
    open_file_cache_valid 120s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

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

配置说明:

  • worker_processes auto:根据 CPU 核心数自动设置进程数。
  • worker_connections 4096:提高单个 worker 的连接数。
  • sendfile on:提高静态文件传输效率。
  • tcp_nopushtcp_nodelay:优化 TCP 数据传输。
  • gzip on:开启 Gzip 压缩,减少传输体积。
  • open_file_cache:缓存文件描述符,减少磁盘读取开销。

修改完成后测试配置:

sudo nginx -t

重载 Nginx:

sudo systemctl reload nginx

四、启用 HTTP/2

如果你的网站使用 HTTPS,建议启用 HTTP/2。HTTP/2 支持多路复用,可以减少请求阻塞,特别适合 CSS、JS、图片较多的网站。

Nginx 站点配置示例:

server {
    listen 443 ssl http2;
    server_name example.com www.example.com;

    root /var/www/example.com;
    index index.php index.html index.htm;

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

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

如果你还没有 HTTPS 证书,可以使用 Certbot 免费申请 Let’s Encrypt 证书:

sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com

证书自动续期测试:

sudo certbot renew --dry-run

五、设置浏览器缓存

浏览器缓存对提升二次访问速度非常明显。对于图片、CSS、JS、字体等静态文件,可以设置较长缓存时间。

在 Nginx 站点配置中加入:

location ~* \.(jpg|jpeg|png|gif|ico|webp|svg|css|js|woff|woff2|ttf|eot)$ {
    expires 30d;
    add_header Cache-Control "public, no-transform";
    access_log off;
}

如果静态资源文件名中带有 hash,例如:

app.8f3a9c1.css
main.6a91b2e.js

可以设置更长的缓存时间:

location ~* \.(css|js|jpg|jpeg|png|webp|gif|svg|woff2?)$ {
    expires 365d;
    add_header Cache-Control "public, immutable";
    access_log off;
}

需要注意的是,如果你没有使用文件名 hash,静态资源缓存太久可能导致用户访问旧文件。因此,生产环境推荐使用构建工具给静态资源加版本号或 hash。


六、PHP-FPM 性能优化

如果你的网站使用 PHP,例如 WordPress、Laravel、ThinkPHP 或 Typecho,那么 PHP-FPM 的配置非常关键。

1. 安装 PHP-FPM

以 PHP 8.2 为例:

sudo apt install -y php-fpm php-cli php-mysql php-curl php-gd php-mbstring php-xml php-zip php-opcache

查看 PHP-FPM 版本:

php -v

2. 配置 Nginx 支持 PHP

站点配置示例:

server {
    listen 80;
    server_name example.com www.example.com;

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

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

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

        fastcgi_connect_timeout 60s;
        fastcgi_send_timeout 120s;
        fastcgi_read_timeout 120s;
        fastcgi_buffer_size 64k;
        fastcgi_buffers 8 64k;
        fastcgi_busy_buffers_size 128k;
        fastcgi_temp_file_write_size 256k;
    }

    location ~ /\.ht {
        deny all;
    }
}

修改后:

sudo nginx -t
sudo systemctl reload nginx

3. 调整 PHP-FPM 进程池

编辑 PHP-FPM 池配置文件:

sudo vim /etc/php/8.2/fpm/pool.d/www.conf

推荐配置示例:

[www]
user = www-data
group = www-data

listen = /run/php/php8.2-fpm.sock
listen.owner = www-data
listen.group = www-data

pm = dynamic
pm.max_children = 30
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 10
pm.max_requests = 500

request_terminate_timeout = 120s

参数说明:

  • pm = dynamic:动态管理 PHP 进程,适合大多数中小型网站。
  • pm.max_children:最大 PHP 子进程数。
  • pm.start_servers:启动时创建的进程数。
  • pm.min_spare_servers:最小空闲进程数。
  • pm.max_spare_servers:最大空闲进程数。
  • pm.max_requests:每个子进程处理一定请求后重启,可避免内存泄漏。

如何估算 pm.max_children

假设服务器有 2GB 可用内存,每个 PHP-FPM 进程平均占用 50MB,则:

2048MB / 50MB ≈ 40

考虑系统、Nginx、数据库也需要内存,可以设置为 20~30。

重启 PHP-FPM:

sudo systemctl restart php8.2-fpm

查看状态:

sudo systemctl status php8.2-fpm

七、开启 OPcache

OPcache 是 PHP 官方提供的字节码缓存,可以避免 PHP 每次请求都重新编译脚本,对 PHP 网站性能提升非常明显。

编辑配置:

sudo vim /etc/php/8.2/fpm/conf.d/10-opcache.ini

参考配置:

zend_extension=opcache.so

opcache.enable=1
opcache.enable_cli=0
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=20000
opcache.validate_timestamps=1
opcache.revalidate_freq=60
opcache.fast_shutdown=1
opcache.save_comments=1

生产环境如果代码不频繁更新,可以设置:

opcache.validate_timestamps=0

这样性能更好,但每次发布代码后需要重启 PHP-FPM:

sudo systemctl restart php8.2-fpm

对于大多数普通站点,建议先使用:

opcache.validate_timestamps=1
opcache.revalidate_freq=60

这样兼顾性能与维护便利性。


八、使用 Redis 做缓存

Redis 是高性能内存数据库,常用于对象缓存、页面缓存、会话缓存等。对于 WordPress、Laravel、ThinkPHP 等应用,使用 Redis 可以显著减少数据库压力。

1. 安装 Redis

sudo apt install -y redis-server php-redis
sudo systemctl enable redis-server
sudo systemctl start redis-server

测试 Redis:

redis-cli ping

如果返回:

PONG

说明 Redis 正常运行。


2. 优化 Redis 配置

编辑配置文件:

sudo vim /etc/redis/redis.conf

推荐调整:

bind 127.0.0.1 ::1
protected-mode yes
maxmemory 256mb
maxmemory-policy allkeys-lru
tcp-keepalive 60
timeout 0

说明:

  • bind 127.0.0.1:只允许本机访问,提高安全性。
  • maxmemory 256mb:限制 Redis 最大内存使用。
  • maxmemory-policy allkeys-lru:内存满时淘汰最近最少使用的 key。

重启 Redis:

sudo systemctl restart redis-server

3. PHP 使用 Redis 示例源码

下面是一个简单的 PHP Redis 缓存示例:

connect('127.0.0.1', 6379);

$key = 'site:home:data';

$data = $redis->get($key);

if ($data === false) {
    // 模拟数据库查询
    $data = [
        'title' => 'Debian 网站性能优化',
        'time' => date('Y-m-d H:i:s'),
        'items' => [
            'Nginx 优化',
            'PHP-FPM 优化',
            'Redis 缓存',
            '数据库优化'
        ]
    ];

    // 缓存 300 秒
    $redis->setex($key, 300, json_encode($data, JSON_UNESCAPED_UNICODE));

    echo "数据来自数据库:\n";
} else {
    $data = json_decode($data, true);

    echo "数据来自 Redis 缓存:\n";
}

print_r($data);

通过这种方式,可以避免高频页面反复访问数据库。


九、MariaDB/MySQL 数据库优化

数据库是很多动态网站的性能瓶颈。即使 Web 服务配置很好,如果数据库慢,整体网站仍然会慢。

1. 安装 MariaDB

sudo apt install -y mariadb-server mariadb-client
sudo systemctl enable mariadb
sudo systemctl start mariadb

安全初始化:

sudo mysql_secure_installation

2. 优化数据库配置

编辑 MariaDB 配置文件:

sudo vim /etc/mysql/mariadb.conf.d/50-server.cnf

[mysqld] 下加入或调整:

[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

max_connections = 200
connect_timeout = 10
wait_timeout = 60
interactive_timeout = 60

innodb_buffer_pool_size = 512M
innodb_log_file_size = 128M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT

query_cache_type = 0
query_cache_size = 0

slow_query_log = 1
slow_query_log_file = /var/log/mysql/mysql-slow.log
long_query_time = 1

说明:

  • innodb_buffer_pool_size:InnoDB 缓冲池,数据库性能关键参数。
  • innodb_flush_log_at_trx_commit = 2:提高写入性能,但极端断电可能丢失约 1 秒事务。
  • slow_query_log:开启慢查询日志,方便分析性能问题。
  • query_cache_type = 0:新版本 MySQL/MariaDB 中查询缓存通常不推荐使用。

重启数据库:

sudo systemctl restart mariadb

查看慢查询日志:

sudo tail -f /var/log/mysql/mysql-slow.log

3. 添加索引优化 SQL

假设有文章表:

CREATE TABLE articles (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    title VARCHAR(255) NOT NULL,
    category_id INT UNSIGNED NOT NULL,
    status TINYINT NOT NULL DEFAULT 1,
    created_at DATETIME NOT NULL,
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

如果经常执行:

SELECT id, title, created_at
FROM articles
WHERE status = 1 AND category_id = 5
ORDER BY created_at DESC
LIMIT 20;

建议添加联合索引:

ALTER TABLE articles
ADD INDEX idx_status_category_created (status, category_id, created_at);

查看执行计划:

EXPLAIN SELECT id, title, created_at
FROM articles
WHERE status = 1 AND category_id = 5
ORDER BY created_at DESC
LIMIT 20;

如果 EXPLAIN 结果中 typeALL,通常说明进行了全表扫描,需要进一步优化索引。


十、启用 FastCGI 页面缓存

对于访问量较大、内容变化不频繁的网站,可以使用 Nginx FastCGI Cache 缓存动态页面。这样用户访问时,Nginx 可以直接返回缓存结果,不必每次都交给 PHP 执行。

1. 在 nginx.conf 中定义缓存区域

编辑:

sudo vim /etc/nginx/nginx.conf

http 模块中加入:

fastcgi_cache_path /var/cache/nginx/fastcgi
    levels=1:2
    keys_zone=PHP_CACHE:100m
    inactive=60m
    max_size=1g;

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

创建缓存目录:

sudo mkdir -p /var/cache/nginx/fastcgi
sudo chown -R www-data:www-data /var/cache/nginx/fastcgi

2. 站点配置 FastCGI Cache

set $skip_cache 0;

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

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

if ($request_uri ~* "/wp-admin/|/admin/|/login|/cart|/checkout") {
    set $skip_cache 1;
}

if ($http_cookie ~* "comment_author|wordpress_logged_in|PHPSESSID") {
    set $skip_cache 1;
}

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php8.2-fpm.sock;

    fastcgi_cache PHP_CACHE;
    fastcgi_cache_valid 200 301 302 10m;
    fastcgi_cache_valid 404 1m;
    fastcgi_cache_bypass $skip_cache;
    fastcgi_no_cache $skip_cache;

    add_header X-FastCGI-Cache $upstream_cache_status;

    include fastcgi_params;
}

配置完成后测试:

sudo nginx -t
sudo systemctl reload nginx

访问网站后查看响应头,如果出现:

X-FastCGI-Cache: HIT

说明页面缓存已命中。

注意:电商、会员中心、后台管理、购物车、支付页面等不适合直接缓存,需要严格排除。


十一、静态资源压缩与前端优化

服务器优化只是网站速度的一部分。很多网站慢,其实是因为前端资源过大。

1. 压缩图片

安装图片压缩工具:

sudo apt install -y jpegoptim optipng webp

压缩 JPG:

jpegoptim --strip-all --max=85 image.jpg

压缩 PNG:

optipng -o2 image.png

转换为 WebP:

cwebp image.jpg -q 80 -o image.webp

WebP 通常比 JPG/PNG 更小,适合现代浏览器。


2. 使用 Nginx 自动优先返回 WebP

如果同时存在 image.jpgimage.jpg.webp,可以让支持 WebP 的浏览器自动访问 WebP。

map $http_accept $webp_suffix {
    default "";
    "~*webp" ".webp";
}

server {
    location ~* \.(png|jpg|jpeg)$ {
        add_header Vary Accept;
        try_files $uri$webp_suffix $uri =404;
        expires 30d;
        access_log off;
    }
}

注意:map 指令必须放在 http 模块中,不能放在 server 模块里。


3. 前端构建压缩示例

如果你使用 Node.js 构建前端资源,可以使用 Vite、Webpack 等工具压缩 CSS 和 JS。

示例 package.json

{
  "scripts": {
    "build": "vite build"
  },
  "devDependencies": {
    "vite": "^5.0.0"
  }
}

执行构建:

npm install
npm run build

构建后通常会生成带 hash 的静态资源文件,例如:

assets/index-2a9f1c3d.js
assets/index-98ac11fe.css

这类文件非常适合设置长期浏览器缓存。


十二、Debian 系统内核参数优化

对于并发量较高的网站,可以适当调整系统网络参数。

编辑:

sudo vim /etc/sysctl.conf

加入以下内容:

net.core.somaxconn = 65535
net.core.netdev_max_backlog = 16384
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_fastopen = 3
fs.file-max = 1000000

应用配置:

sudo sysctl -p

提高文件描述符限制:

sudo vim /etc/security/limits.conf

加入:

www-data soft nofile 65535
www-data hard nofile 65535
root soft nofile 65535
root hard nofile 65535

如果使用 systemd 管理 Nginx,还可以创建覆盖配置:

sudo systemctl edit nginx

加入:

[Service]
LimitNOFILE=65535

重新加载 systemd 并重启 Nginx:

sudo systemctl daemon-reload
sudo systemctl restart nginx

十三、使用 CDN 提升访问速度

如果用户分布在多个地区,仅靠单台 Debian 服务器很难保证所有地区访问都快。CDN 可以将静态资源缓存到离用户更近的节点。

适合放 CDN 的资源:

  • 图片
  • CSS
  • JS
  • 字体文件
  • 视频封面
  • 下载文件

不建议随便缓存的内容:

  • 用户中心
  • 购物车
  • 支付页面
  • 后台管理
  • 带用户隐私信息的接口

使用 CDN 时,建议开启:

静态资源缓存
HTTPS
HTTP/2 或 HTTP/3
Brotli 压缩
防盗链
源站保护

如果源站是 Nginx,需要正确获取真实 IP。例如 Cloudflare 可使用:

set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
real_ip_header CF-Connecting-IP;

不同 CDN 的真实 IP 头字段可能不同,需要参考服务商文档。


十四、日志分析与性能监控

优化不能靠感觉,一定要依靠数据。

1. 查看 Nginx 访问日志中最慢请求

如果你的日志格式包含请求时间,可以这样分析。先在 Nginx 中定义日志格式:

log_format main_ext '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$request_time" "$upstream_response_time"';

启用:

access_log /var/log/nginx/access.log main_ext;

分析耗时较高的请求:

awk '{print $NF, $0}' /var/log/nginx/access.log | sort -nr | head -20

2. 使用 goaccess 查看网站访问情况

安装:

sudo apt install -y goaccess

生成 HTML 报告:

goaccess /var/log/nginx/access.log -o /var/www/html/report.html --log-format=COMBINED

然后访问:

http://example.com/report.html

建议给报告页面加访问限制,避免暴露敏感数据。


十五、一键检查网站速度的简单脚本源码

下面提供一个简单的 Bash 脚本,用于检测网站响应时间、HTTP 状态码、页面大小等信息。

创建脚本:

vim check_site_speed.sh

源码如下:

#!/bin/bash

URL="$1"

if [ -z "$URL" ]; then
    echo "用法: $0 https://example.com"
    exit 1
fi

echo "正在检测:$URL"
echo "--------------------------------"

curl -o /dev/null -s -w \
"HTTP状态码: %{http_code}
DNS解析时间: %{time_namelookup}s
TCP连接时间: %{time_connect}s
TLS握手时间: %{time_appconnect}s
首字节时间: %{time_starttransfer}s
总耗时: %{time_total}s
下载大小: %{size_download} bytes
下载速度: %{speed_download} bytes/s
" "$URL"

echo "--------------------------------"
echo "检测完成"

赋予执行权限:

chmod +x check_site_speed.sh

使用方法:

./check_site_speed.sh https://example.com

输出示例:

HTTP状态码: 200
DNS解析时间: 0.012345s
TCP连接时间: 0.045678s
TLS握手时间: 0.089123s
首字节时间: 0.156789s
总耗时: 0.320456s
下载大小: 48231 bytes
下载速度: 150500 bytes/s

其中最值得关注的是:

  • time_namelookup:DNS 解析时间
  • time_connect:TCP 连接时间
  • time_appconnect:HTTPS 握手时间
  • time_starttransfer:首字节时间,通常反映后端处理速度
  • time_total:总耗时

如果首字节时间很高,通常说明后端、数据库或缓存存在问题;如果下载时间高,可能是页面体积太大或网络带宽不足。


十六、完整 Nginx + PHP-FPM 站点配置示例

下面给出一个比较完整的站点配置,可作为 Debian 网站优化模板。

server {
    listen 80;
    server_name example.com www.example.com;

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

server {
    listen 443 ssl http2;
    server_name example.com www.example.com;

    root /var/www/example.com/public;
    index index.php index.html;

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

    access_log /var/log/nginx/example.access.log;
    error_log /var/log/nginx/example.error.log warn;

    client_max_body_size 50m;

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

    location ~* \.(jpg|jpeg|png|gif|ico|webp|svg|css|js|woff|woff2|ttf|eot)$ {
        expires 30d;
        add_header Cache-Control "public, no-transform";
        access_log off;
        try_files $uri =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;

        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;

        fastcgi_connect_timeout 60s;
        fastcgi_send_timeout 120s;
        fastcgi_read_timeout 120s;

        fastcgi_buffer_size 64k;
        fastcgi_buffers 8 64k;
        fastcgi_busy_buffers_size 128k;
    }

    location ~ /\. {
        deny all;
    }
}

启用站点:

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

十七、优化顺序建议

如果你不知道从哪里开始,可以按照以下顺序进行:

  1. 先测量速度

    • 使用 curl
    • 使用浏览器 DevTools
    • 使用 PageSpeed Insights
    • 使用 GTmetrix
  2. 开启 HTTPS + HTTP/2

    • 提升并发请求效率
    • 改善安全性和 SEO
  3. 启用 Gzip 或 Brotli

    • 减少文本资源体积
  4. 设置静态资源缓存

    • 提高二次访问速度
  5. 开启 PHP OPcache

    • PHP 网站必做优化
  6. 接入 Redis

    • 减少数据库查询
  7. 优化数据库索引

    • 解决慢查询
  8. 根据流量考虑 FastCGI Cache

    • 对内容站、博客、新闻站效果显著
  9. 压缩图片和前端资源

    • 降低页面总大小
  10. 接入 CDN

    • 提升跨地域访问速度

十八、常见误区

1. 盲目把 PHP-FPM 进程数调很大

pm.max_children 并不是越大越好。设置过大可能导致内存耗尽,服务器开始使用 swap,网站反而更慢。

2. 所有页面都做缓存

登录页面、用户中心、订单页面、购物车页面不能随便缓存,否则可能出现用户数据错乱甚至隐私泄露。

3. 只看首页速度

很多网站首页很快,但搜索页、分类页、后台接口很慢。应重点分析真实用户访问频率高、耗时长的页面。

4. 不看慢查询日志

数据库问题不能靠猜。开启慢查询日志后,才能准确知道哪些 SQL 需要优化。

5. 忽视图片体积

很多网站服务器响应很快,但页面加载仍然慢,是因为图片过大。图片优化往往比服务器参数调整更有效。


十九、总结

在 Debian 上提高网站速度,需要从系统、Web 服务、PHP、数据库、缓存、前端资源和网络分发多个层面综合优化。对于大多数中小型网站来说,以下几项优化收益最大:

  • Nginx 开启 Gzip、HTTP/2、静态资源缓存;
  • PHP 开启 OPcache,并合理调整 PHP-FPM;
  • 使用 Redis 缓存热点数据;
  • 优化 MariaDB/MySQL 参数和 SQL 索引;
  • 对动态页面使用 FastCGI Cache;
  • 压缩图片,使用 WebP;
  • 使用 CDN 加速静态资源;
  • 通过日志和脚本持续监控网站性能。

网站性能优化不是一次性工作,而是持续迭代的过程。建议每次只修改一类配置,然后通过响应时间、CPU、内存、数据库慢查询、缓存命中率等指标观察效果。只有基于数据优化,才能真正让 Debian 网站稳定、快速、可扩展。

目录结构
全文