源码可参考:random-pic-api。本文采用一个 PHP 入口而不是复制三份脚本,并将应用和图片目录分离。PHP 7.4 已结束支持;请使用发行版当前仍受支持的 PHP-FPM 包,并以本机实际安装的 FPM socket 为准。

前提与目录

以下示例面向 Debian/Ubuntu。先更新软件包索引,查看可用版本;不同发行版的 PHP 主版本和 socket 名称不同,不应照抄旧版本号。

1
2
3
4
5
sudo apt update
apt-cache policy php-fpm
sudo apt install nginx php-fpm php-cli
php -v
systemctl list-units --type=socket 'php*-fpm.sock'

创建统一目录。www-data 只需读取图片和应用,不应拥有图片源文件;由管理员或单独的导入任务写入图片。

1
2
3
4
5
6
7
8
sudo mkdir -p -m 0750 /srv/random-image-api/app/public
sudo chown root:www-data /srv/random-image-api/app/public
sudo mkdir -p -m 0750 /srv/random-image-api/images/landscape
sudo chown root:www-data /srv/random-image-api/images/landscape
sudo mkdir -p -m 0750 /srv/random-image-api/images/portrait
sudo chown root:www-data /srv/random-image-api/images/portrait
sudo install -m 0640 -o root -g www-data /dev/null /srv/random-image-api/app/public/random.php
sudo editor /srv/random-image-api/app/public/random.php

将横向图片放入 /srv/random-image-api/images/landscape,竖向图片放入 /srv/random-image-api/images/portrait。目录名、PHP 配置和图片处理脚本必须保持一致。

PHP 入口

将以下内容写入 /srv/random-image-api/app/public/random.php。脚本以 finfo 检查实际 MIME 类型,而非只相信扩展名;缺少 User-Agent 时按桌面端处理;目录不存在、不可读或没有允许格式的图片时返回明确错误而不会调用 readfile(false)。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
declare(strict_types=1);

$imageRoots = [
    'landscape' => '/srv/random-image-api/images/landscape',
    'portrait' => '/srv/random-image-api/images/portrait',
];
$allowedMimeTypes = [
    'image/jpeg' => true,
    'image/png' => true,
    'image/gif' => true,
    'image/webp' => true,
];

function fail(int $status, string $message): never
{
    http_response_code($status);
    header('Content-Type: text/plain; charset=utf-8');
    header('Cache-Control: no-store');
    exit($message . "\n");
}

$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$isMobile = preg_match('/android|iphone|ipad|ipod|blackberry|windows phone/i', $userAgent) === 1;
$directory = $imageRoots[$isMobile ? 'portrait' : 'landscape'];

if (!is_dir($directory) || !is_readable($directory)) {
    fail(503, 'Image directory is unavailable.');
}

$files = [];
$finfo = new finfo(FILEINFO_MIME_TYPE);
foreach (new DirectoryIterator($directory) as $file) {
    if (!$file->isFile() || $file->isLink() || !$file->isReadable()) {
        continue;
    }

    $mime = $finfo->file($file->getPathname());
    if (isset($allowedMimeTypes[$mime])) {
        $files[] = ['path' => $file->getPathname(), 'mime' => $mime];
    }
}

if ($files === []) {
    fail(404, 'No supported image is available.');
}

$image = $files[random_int(0, count($files) - 1)];
header('Content-Type: ' . $image['mime']);
header('Content-Length: ' . (string) filesize($image['path']));
header('Cache-Control: no-store, max-age=0');
header('X-Content-Type-Options: nosniff');
readfile($image['path']);

先只做语法检查,再继续配置 Web 服务:

1
sudo php -l /srv/random-image-api/app/public/random.php

Nginx 与 PHP-FPM

先备份现有站点配置。下面的 fastcgi_pass 是常见的发行版无版本别名;若 systemctl list-units 显示的是版本化 socket,例如 /run/php/php8.x-fpm.sock,必须替换为该实际路径。不要暴露 PHP 通配 location,也不要把图片目录放进 Web 根目录。

1
2
sudo cp -a /etc/nginx/conf.d /etc/nginx/conf.d.backup.$(date +%F-%H%M%S)
sudo editor /etc/nginx/conf.d/random-image-api.conf
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
server {
    listen 80;
    listen [::]:80;
    server_name images.example.com;

    root /srv/random-image-api/app/public;
    index random.php;
    server_tokens off;

    location = / {
        return 302 /random.php;
    }

    location = /random.php {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        fastcgi_pass unix:/run/php/php-fpm.sock;
        fastcgi_read_timeout 15s;
    }

    # This application has exactly one executable endpoint.
    location ~ \.php$ {
        return 404;
    }

    location ~ /\. {
        deny all;
    }

    location / {
        try_files $uri =404;
    }
}

验证语法后再重载;保留当前 SSH 会话,直到确认请求成功。

1
2
3
4
5
sudo nginx -t
sudo systemctl reload nginx
curl -I http://127.0.0.1/random.php -H 'Host: images.example.com'
sudo tail -n 50 /var/log/nginx/error.log
sudo journalctl -u php*-fpm --since '10 minutes ago'

随机响应不能被共享缓存固定住,因此 PHP 响应使用 Cache-Control: no-store。如前置 CDN 或反向代理,请为 /random.php 关闭缓存或以查询参数显式区分缓存键;图片内容本身不经 URL 直接公开时,不要对该接口设置长缓存。

HTTPS

先确认域名 A/AAAA 记录指向本机,并在防火墙和云安全组放行 TCP 80、443。只能选择一种签发方式:HTTP-01 的 Nginx 插件适合 80 端口可从公网访问的普通域名;DNS-01 适合通配符证书或不便开放 HTTP 校验的环境。完整的仓库安装、证书流程和回滚说明见 Nginx 反代 HTTPS 指南。

签发成功后将站点调整为 HTTPS。证书名称由 Certbot 实际输出决定,以下使用域名示例。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
server {
    listen 80;
    listen [::]:80;
    server_name images.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name images.example.com;

    ssl_certificate /etc/letsencrypt/live/images.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/images.example.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;

    root /srv/random-image-api/app/public;

    location = /random.php {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass unix:/run/php/php-fpm.sock;
    }

    location ~ \.php$ { return 404; }
    location ~ /\. { deny all; }
    location / { try_files $uri =404; }
}

图片整理脚本

以下 Python 脚本将输入目录中的 JPEG、PNG 和 WebP 处理到同一项目的图片路径。它创建目标目录、按方向分类、跳过超大像素图,并避免覆盖同名文件。先在副本上运行;这不是在线服务的一部分。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from pathlib import Path
from PIL import Image, UnidentifiedImageError

SOURCE = Path('/srv/random-image-api/import')
LANDSCAPE = Path('/srv/random-image-api/images/landscape')
PORTRAIT = Path('/srv/random-image-api/images/portrait')
MAX_PIXELS = 178_956_970
EXTENSIONS = {'.jpg', '.jpeg', '.png', '.webp'}

def destination(folder: Path, source: Path) -> Path:
    candidate = folder / f'{source.stem}.webp'
    suffix = 1
    while candidate.exists():
        candidate = folder / f'{source.stem}-{suffix}.webp'
        suffix += 1
    return candidate

for folder in (LANDSCAPE, PORTRAIT):
    folder.mkdir(parents=True, exist_ok=True)

for source in SOURCE.iterdir():
    if not source.is_file() or source.suffix.lower() not in EXTENSIONS:
        continue
    try:
        with Image.open(source) as image:
            image.load()
            if image.width * image.height > MAX_PIXELS:
                print(f'Skip oversized image: {source.name}')
                continue
            target_dir = LANDSCAPE if image.width > image.height else PORTRAIT
            image.convert('RGB').save(destination(target_dir, source), 'WEBP', quality=85, method=6)
    except (OSError, UnidentifiedImageError) as error:
        print(f'Cannot process {source.name}: {error}')

备份、更新与回滚

备份应用、图片和 Nginx 配置;证书私钥只应进入受控的加密备份。修改前执行 php -l 与 nginx -t。PHP 更新应通过发行版安全更新完成,更新 FPM 后检查 socket 路径是否变化。

1
2
3
4
5
sudo tar -C /srv -czf /root/random-image-api-$(date +%F).tar.gz random-image-api
sudo cp -a /etc/nginx/conf.d/random-image-api.conf /root/random-image-api.conf.$(date +%F)
sudo apt update && sudo apt upgrade
sudo php -l /srv/random-image-api/app/public/random.php
sudo nginx -t && sudo systemctl reload nginx

若新配置失败,不要重载:恢复刚才的配置备份,重新执行 nginx -t,再 reload。若已重载导致服务异常,使用仍保存的备份恢复并查看 /var/log/nginx/error.log 与 PHP-FPM journal;图片误删则从 tar 备份恢复到相同的 /srv/random-image-api/images 路径并保持只读权限。

参考资料