1. 环境准备与规划

1.1 服务器角色分配

角色

数量

配置建议

说明

Varnish缓存

2

4CPU/8GB/50GB

建议使用内存型实例

Nginx前端

2

4CPU/8GB/100GB

开启HTTP/3支持

PHP-FPM

3

8CPU/16GB/50GB

根据业务扩展

MySQL主从

3

8CPU/32GB/500GB

SSD存储,主从复制

1.2 网络规划

# 建议网络拓扑
用户 → CDN → Varnish(80/443) → Nginx(8080) → PHP-FPM(9000)
                                   ↘
                                   直接访问静态资源

2. 组件安装与配置

2.1 Varnish 7.3 安装配置

安装(Ubuntu/Debian):

sudo apt update
sudo apt install -y varnish

配置 /etc/varnish/default.vcl

vcl 4.1;

backend default {
    .host = "nginx_server_ip";
    .port = "8080";
    .connect_timeout = 5s;
    .first_byte_timeout = 30s;
    .between_bytes_timeout = 60s;
}

sub vcl_recv {
    # 绕过缓存的条件
    if (req.url ~ "^/admin" || req.method != "GET") {
        return(pass);
    }

    # 处理压缩
    if (req.http.Accept-Encoding) {
        if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|mp3|mp4|m4a|ogg|woff|woff2|eot|ttf|otf)(\?.*|)$") {
            unset req.http.Accept-Encoding;
        } elsif (req.http.Accept-Encoding ~ "gzip") {
            set req.http.Accept-Encoding = "gzip";
        } elsif (req.http.Accept-Encoding ~ "br") {
            set req.http.Accept-Encoding = "br";
        } else {
            unset req.http.Accept-Encoding;
        }
    }

    # 移除Cookie对静态资源的影响
    if (req.url ~ "^/[^?]*\.(7z|avi|bmp|csv|doc|docx|eot|flac|flv|gif|gz|ico|jpeg|jpg|js|json|mp3|mp4|mpeg|pdf|png|ppt|rar|svg|swf|tar|txt|wav|webp|woff|woff2|xls|xlsx|xml|zip)(\?.*)?$") {
        unset req.http.Cookie;
    }
}

sub vcl_backend_response {
    # 设置缓存时间
    if (bereq.url ~ "^/[^?]*\.(7z|avi|bmp|csv|doc|docx|eot|flac|flv|gif|gz|ico|jpeg|jpg|js|json|mp3|mp4|mpeg|pdf|png|ppt|rar|svg|swf|tar|txt|wav|webp|woff|woff2|xls|xlsx|xml|zip)(\?.*)?$") {
        set beresp.ttl = 365d;
    } else {
        set beresp.ttl = 2h;
    }

    # 处理ESI片段
    if (beresp.http.content-type ~ "text/html") {
        set beresp.do_esi = true;
    }
}

系统调优 /etc/default/varnish

# 调整内存缓存大小(建议可用内存的70%)
VARNISH_STORAGE_SIZE=6G

# 监听端口
VARNISH_LISTEN_PORT=80

# 线程池配置
VARNISH_THREAD_POOLS=4
VARNISH_THREAD_POOL_MAX=4000

2.2 Nginx 1.25 配置

安装(带HTTP/3支持):

# Ubuntu
sudo apt install -y nginx-full libnginx-mod-http-quic

# 编译安装(推荐)
wget https://nginx.org/download/nginx-1.25.3.tar.gz
tar zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.3
./configure --with-http_ssl_module --with-http_v2_module --with-http_v3_module
make && sudo make install

主配置 /etc/nginx/nginx.conf

user www-data;
worker_processes auto;
worker_rlimit_nofile 100000;

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

http {
    # 基础设置
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 30;
    types_hash_max_size 2048;
    server_tokens off;

    # MIME类型
    include mime.types;
    default_type application/octet-stream;

    # 日志格式
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    # Gzip配置
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    # 缓存路径
    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=STATIC:100m inactive=24h max_size=1g;

    # 加载虚拟主机配置
    include /etc/nginx/conf.d/*.conf;
}

站点配置示例 /etc/nginx/conf.d/example.com.conf

server {
    listen 8080 reuseport;
    listen [::]:8080 reuseport;
    server_name example.com;

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

    # 静态文件缓存
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2)$ {
        expires 365d;
        add_header Cache-Control "public, immutable";
        access_log off;
    }

    # PHP处理
    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_read_timeout 300;
    }

    # 禁止访问敏感文件
    location ~ /\.(ht|git|svn) {
        deny all;
    }
}

2.3 PHP-FPM 8.2 优化

sudo apt install -y php8.2-fpm php8.2-mysql php8.2-opcache php8.2-redis

配置 /etc/php/8.2/fpm/php.ini

memory_limit = 256M
max_execution_time = 120
upload_max_filesize = 64M
post_max_size = 72M
opcache.enable = 1
opcache.memory_consumption = 256
opcache.max_accelerated_files = 20000
opcache.validate_timestamps = 0 ; 生产环境建议禁用

进程池优化 /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 = 100
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 30
pm.max_requests = 1000

slowlog = /var/log/php-fpm/slow.log
request_slowlog_timeout = 5s

2.4 MySQL 8.0 配置

优化 /etc/mysql/mysql.conf.d/mysqld.cnf

[mysqld]
innodb_buffer_pool_size = 12G  # 总内存的50-70%
innodb_log_file_size = 2G
innodb_flush_log_at_trx_commit = 1
innodb_flush_method = O_DIRECT
innodb_file_per_table = 1
innodb_thread_concurrency = 0
innodb_read_io_threads = 16
innodb_write_io_threads = 16

max_connections = 500
thread_cache_size = 100

query_cache_type = 0
query_cache_size = 0

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

3. 缓存策略设计

3.1 Varnish 缓存规则

# 在vcl_recv中添加
if (req.url ~ "^/product/(\d+)") {
    set req.url = "/product/" + regsub(req.url, "^/product/(\d+).*", "\1");
}

# 在vcl_backend_response中添加
if (bereq.url ~ "^/api/") {
    set beresp.ttl = 10m;
    set beresp.http.Cache-Control = "max-age=600";
}

3.2 Nginx 多级缓存

location / {
    proxy_pass http://php_backend;
    proxy_cache STATIC;
    proxy_cache_key "$scheme$request_method$host$request_uri";
    proxy_cache_valid 200 302 10m;
    proxy_cache_valid 404 1m;
    add_header X-Cache-Status $upstream_cache_status;
}

4. 高可用部署

4.1 Varnish 集群配置

# 安装varnish-agent
sudo apt install varnish-agent

# 配置集群同步
varnishadm -S /etc/varnish/secret -T localhost:6082 backend.set_health default probe

4.2 Nginx 负载均衡

upstream php_backend {
    zone backend 64k;
    server 10.0.1.10:9000 weight=3;
    server 10.0.1.11:9000;
    server 10.0.1.12:9000 backup;
    
    keepalive 32;
    keepalive_requests 1000;
}

5. 安全加固措施

5.1 Varnish 安全

# 阻止常见攻击
sub vcl_recv {
    if (req.http.User-Agent ~ "(nikto|wget|scan|bot|spider)") {
        return(synth(403, "Forbidden"));
    }
}

5.2 Nginx 安全头

add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'";

5.3 PHP 安全

disable_functions = exec,passthru,shell_exec,system
expose_php = Off

6. 监控与维护

6.1 Varnish 监控

varnishstat -1 -f MAIN.cache_hit,MAIN.cache_miss
varnishtop -i BereqURL

6.2 Nginx 状态监控

location /nginx_status {
    stub_status on;
    access_log off;
    allow 127.0.0.1;
    deny all;
}

6.3 MySQL 监控

-- 安装performance_schema
INSTALL PLUGIN performance_schema SONAME 'performance_schema.so';

7. 自动化部署脚本

7.1 一键部署脚本

#!/bin/bash
# deploy_lnmp_varnish.sh

# 安装Varnish
apt install -y varnish
cp varnish.vcl /etc/varnish/default.vcl
systemctl restart varnish

# 安装Nginx
apt install -y nginx
cp nginx.conf /etc/nginx/
nginx -t && systemctl restart nginx

# 安装PHP
apt install -y php-fpm php-mysql
cp php.ini /etc/php/8.2/fpm/
systemctl restart php8.2-fpm

# 安装MySQL
apt install -y mysql-server
cp mysqld.cnf /etc/mysql/mysql.conf.d/
systemctl restart mysql

性能调优命令

# Varnish调优
varnishadm param.set thread_pool_max 5000

# Nginx调优
echo "net.ipv4.tcp_max_syn_backlog = 4096" >> /etc/sysctl.conf

# PHP-FPM调优
php-fpm8.2 -tt | grep "max children"

# MySQL调优
mysql -e "SHOW GLOBAL STATUS LIKE 'Innodb_buffer%';"

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐