2016-10-26 66 views
0

我有這樣的nginx的配置:Nginx的前端和後端下URL

server{ 
    listen  80; 
    server_name  hans.site.dev; 

    location/{ 
     index  index.html index.php; 
     root /var/www/a/public; 
    } 

    location /api { 
     root /var/www/b/public; 
     index index.php index.html index.htm; 
     try_files $uri /api/$uri/ /index.php?$query_string; 

     location ~ \.php$ { 
      fastcgi_pass unix:/var/run/php/php7.1-fpm.sock; 
      fastcgi_index index.php; 
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 
      include  fastcgi_params; 

      fastcgi_split_path_info  ^(.+\.php)(/.+)$; 
      fastcgi_param PATH_INFO  $fastcgi_path_info; 
      fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; 
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 
     } 
    } 
} 

其中:

  • 答:前端(角)
  • B:後端(流明)

以後我想補充

  • C:管理員(角)
  • d:支持(角)

但即使這樣的配置,當我嘗試訪問hans.site.dev/api/,它會給我此錯誤: 「/ var/www/a /public/index.php」failed(2:No such file or directory),client:192.168.56.1,server:hans.site.dev,request:「 GET/api/HTTP/1.1「,主機:」hans.site.dev「。

爲什麼它是指一個,而不是b?以及如何解決它?

+0

注意,現在你的'/ api'位置查找這樣的文件: '在/ var/WWW/B /公/ api'。在這種情況下,你應該使用'alias'。 http://nginx.org/en/docs/http/ngx_http_core_module.html#alias 所以你會被重定向到'/index.php?$ query_string;' –

回答

1

您的try_files聲明不正確。

  • 裏面的location /api塊中,$uri變量已經包含了/api前綴。

  • 的默認操作目前向客戶機發送給其他一些index.php,而不是期望的位置/api/index.php

試試這個:

location /api { 
    root /var/www/b/public; 
    index index.php index.html index.htm; 
    try_files $uri $uri/ /api/index.php?$query_string; 

在這種配置中,所有文件都位於目錄結構:

/var/www/b/public/api/ 

請注意/api是最終的目錄組件。

編輯:如果您必須使用alias指令,請注意這個open issue關於使用try_files。因此您的try_files函數需要使用if語句重新實現。注意this caution關於使用if指令。

root替換爲aliastry_files替換爲離散if語句。 if塊的內容是有限的,所以我們只使用rewrite ... last語句。

index指令是使用多個if語句實現的(它們都是非常必要的)。這可能有更好的方法。

SCRIPT_FILENAME設置爲$request_filename這是別名路徑名。

location /api { 
    alias /var/www/b/public; 

    if (-f $request_filename/index.php) { rewrite^$uri/index.php last; } 
    if (-f $request_filename/index.html) { rewrite^$uri/index.html last; } 
    if (-f $request_filename/index.htm) { rewrite^$uri/index.htm last; } 
    if (!-f $request_filename) { rewrite^/api/index.php last; } 

    location ~ \.php$ { 
     include  fastcgi_params; 

     fastcgi_pass unix:/var/run/php/php7.1-fpm.sock; 
     fastcgi_param SCRIPT_FILENAME $request_filename; 
    } 
} 
+0

失敗,這真的是make/api引用/ var/WWW/b /公衆?因爲我的端點是/api/index.php = /var/www/b/public/index.php。 –

+0

嘗試將PHP應用程序從'/ api'別名到'/ public'可以完成,但相當複雜。最簡單的解決方案是重命名/移動目錄。 –

+0

重命名或移動是不允許的,我正在尋找真正的解決方案,因爲我們有幾個這樣的,我必須嘗試幾個配置 –