我有一種情況,我需要處理https://example.com/api/v1
來自不同檔案夾的所有請求,比如說/var/www/firstversion/public來自https://example.com/api/v2其他檔案夾/var/www/secondversion/public
以下是我當前配置的樣子
server {
root /var/www/firstversion/public/;
index index.html index.php index.htm index.nginx-debian.html;
server_name example.com;
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location /api/v2/ {
alias /var/www/secondversion/public/;
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
這里的問題是我總是從/var/www/firstversion/public/. 但是,為了驗證是否選擇了位置塊,我嘗試添加return 302 https://google.com并且它有效。所以位置模式是匹配的,但不知何故alias/root不起作用。有人可以指出正確的方向還是我錯過了什么?
uj5u.com熱心網友回復:
您缺少的第一件事是最后一個try_files指令引數被視為新的 URI 以從頭開始重新評估。也就是說,在/api/v2/some/route您處理了類似的請求location /api/v2/ { ... }并且您的本地檔案系統上沒有這樣的物理檔案或目錄之后,就會發生/var/www/secondversion/public/some/route內部重寫。/index.php$is_args$args之后,重寫的 URI 將由您的PHP-FPM 處理程式處理,該處理程式從上層配置級別location ~ \.php$ { ... }繼承其根。/var/www/firstversion/public/
與該try_files指令一起使用時的指令alias具有長期存在的副作用,我認為至少在主要的 nginx 版本發生更改之前不會修復,因為存在太多的配置以某種方式采用這些效果。當您需要在某個 URI 前綴下托管一些復雜的基于 PHP 的系統(例如 WordPress)時,可以使用此處所示的解決方法,并宣告嵌套的 PHP 處理程式。但是,您的情況完全不同,實際上只提供一些 API,您不需要如此復雜的方法。
您應該明白,您根本不需要堅持location ~ \.php$ { ... }通過 PHP-FPM 守護行程處理 PHP 檔案,也不需要堅持使用某種預定義的 PHP 處理程式snippets/fastcgi-php.conf(我想這是如這里所示)。相反,如果所有請求都應該index.php由第一個或第二個后端應用程式專門處理,您可以自由地以如下方式定義您的自定義 PHP 處理程式:
map $uri $api_root {
~^/api/v2 /var/www/secondversion/public;
default /var/www/firstversion/public;
}
server {
...
location ^~ /api/ {
include fastcgi_params;
# redefine some FastCGI parameters
fastcgi_param DOCUMENT_ROOT $api_root;
fastcgi_param SCRIPT_NAME /index.php;
fastcgi_param SCRIPT_FILENAME $api_root/index.php;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/476737.html
