Nginx

Nginx本地代理 - 上游萬用字元?

  • November 30, 2017

如果瀏覽web.dev/test2的話,就會進去看看/var/www/testsite/test2.local/public。全部通過本地代理完成。

下面的重寫僅完美執行test2

upstream site.local {
   server 127.0.0.1;
}
server {
   server_name web.dev;
   root   /var/www/web.dev/public;
   index  index.php;
   try_files $uri $uri/ /index.php?$args;
   location ~ \.php$ {
       include         fastcgi_params;
       fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
       fastcgi_pass    unix:/run/php/php7.0-fpm.sock;
   }
   location /test2 {
       proxy_pass http://site.local/;
   }
}
server {
   server_name site.local;
   root /var/www/testsite/test2.local/public;
   index  index.php;
   try_files $uri $uri/ /index.php?$args;
   location ~ \.php$ {
       include         fastcgi_params;
       fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
       fastcgi_pass    unix:/run/php/php7.0-fpm.sock;
   }
}

我有數百個/test3,,/test4等等。我不想server為每個人編寫單獨的指令,因為它太長太乏味了。

以下是我到目前為止所做的萬用字元:

upstream *.local {
   server 127.0.0.1;
}
server {
   server_name web.dev;
   root   /var/www/web.dev/public;
   index  index.php;
   try_files $uri $uri/ /index.php?$args;
   location ~ \.php$ {
       include         fastcgi_params;
       fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
       fastcgi_pass    unix:/run/php/php7.0-fpm.sock;
   }
   location /(?<mytestsite>[^/]+) {
       proxy_pass http://$mytestsite.local/;
   }
}
server {
   server_name *.local;
   root /var/www/testsite/$host/public;
   index  index.php;
   try_files $uri $uri/ /index.php?$args;
   location ~ \.php$ {
       include         fastcgi_params;
       fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
       fastcgi_pass    unix:/run/php/php7.0-fpm.sock;
   }
}

它行不通。upstream不接受萬用字元。使用正則表達式.*upstream不起作用。

嘗試使用地圖。就像是

map $http_host $backend {
  host1 backend1;
  host2 backend2;
  default backend1;
}

upstream backend {
   server $backend.site.tld # nginx won't recognise .local unless in DNS
}

可能會奏效。我不能保證這一點,因為我目前無法對其進行測試,但這是在低級別處理變數的一般途徑。

更新:nginx 需要在啟動時知道它的後端,所以你在你的上游指令中定義它們:

upstream backend {
   server server1.site.tld;
   server server2.site.tld;
   ...
}

然後proxy_pass從地圖上設置你的:

proxy_pass   $backend;

引用自:https://serverfault.com/questions/885906