Nginx - PHP 的條件 proxy_pass

Nginx - PHP 的條件 proxy_pass

我的下面的配置似乎目前僅適用於靜態文件,但對於 PHP 文件來說太貪婪了。

這是一個新的前端伺服器,我們正在慢慢地將 PHP 腳本和內容遷移到其中。

邏輯是:如果檔案存在於本機(在 /var/www/test.com 中),則提供該檔案。否則發送到 10.0.1.2 伺服器來提供內容。

對於靜態內容,這效果很好。 (.html、.jpg、.txt 等)。

然而對於 PHP 來說,這個配置太貪婪了,即使該檔案不在本機檔案系統上,它也會嘗試執行任何 .php 檔案。

有沒有辦法僅在本機檔案系統上找到該檔案時才運行它,如果沒有,則執行與靜態內容相同的操作並將其發送到 10.0.1.2 伺服器?

server {
    listen 80;

    server_name www.test.com;

    root /var/www/test.com;

    location / {
        try_files $uri @proxy;
    }

    location @proxy {
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass https://10.0.1.2;
    }

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

答案1

因此,不允許 try_files 重複,但以下內容有效...

server {
    listen 80;

    server_name www.test.com;

    root /var/www/test.com;

    location / {
        try_files $uri @proxy;
    }

    location @proxy {
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass https://10.0.1.2;
    }

    location ~ \.php$ {
        error_page 404 = @proxy;
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
    }
}

相關內容