仅当 Nginx 不存在文件时才将 URL 重定向到 PHP


Redirect URL to PHP only if file does not exist with Nginx

我试图让Nginx重写URL空间./data/(.+).png来服务Image.php?guid=$1

server {
    server_name my.server;
    listen 80;
    listen 127.0.0.1:80;
    root /var/www/my.server;
    index index.html;
    location / {
        try_files $uri $uri/ index.html;
        rewrite ^/data/(.+).png serveImage.php?guid=$1 last;
    }
    location ~ '.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param HTTPS off;
    }
}

我做错了什么? serveImage.php确实存在于文档根目录中。

重写

似乎没有按计划工作(似乎没有访问.log或错误.log甚至暗示规则甚至被抓住了)。我制作了一个更通用的路由器,可能更适合其他未知的需求。

location / {
    try_files $uri $uri/ @router;
    index index.html index.php;
    error_page 403 = @router;
    error_page 404 = @router;
}
location @router {
    rewrite ^(.*)$ /router.php?$1;
}

好吧,如果它总是/data我会为它创建一个特定的位置,就像这样

location ~ /data/(.+).png {
    try_files $uri /serveImage.php?guid=$1;
}

试试这个,告诉我它是否有效。