2017-03-02 80 views
0

我有nginx的網站上10.0.0.1簡單的配置文件:nginx的上游配置

default.conf

server { 
    listen  80; 
    server_name server.com; 

    location/{ 
     root /www; 
     index index.html; 
    } 

此外,我想請求重定向到http://10.0.0.1/app1 3與相同的應用程序的端口8888的服務器,如:

http://10.0.0.1/app1 - >http://10.0.0.(2,3,4):8888/app1

所以我必須添加到我的default.conf這樣的配置均衡:

upstream app1 { 
    server 10.0.0.2:8888; 
    server 10.0.0.3:8888; 
    server 10.0.0.4:8888; 
} 

server { 
    listen 80; 

    location /app1/ { 
     rewrite ^/app1^/ /$1 break; 
     proxy_pass http://app1; 
    } 
} 

,但我想保持在一個單獨的文件這個平衡配置 - app1.conf。

如果我有/etc/nginx/conf.d/文件夾我只能打開URL http://10.0.0.1/

但是當我打開http://10.0.0.1/app1我得到的,因爲default.conf的錯誤404它試圖找到這兩配置文件app1在/ www中,甚至不會嘗試檢查app1.conf的平衡規則。 因此,它似乎只能用於default.conf配置文件。 如何解決它?

+0

我想說的原因是你用了相同的兩個服務器塊監聽端口。它與兩個配置文件/目錄無關。 – unNamed

+0

感謝您的建議。但似乎我不能在服務器塊外使用位置指令,並且如果我在app1.conf中更改端口號 - nginx開始偵聽那個不符合我的條件的端口 - 我需要打開URL「http://10.0 .0.1/app1「 –

回答

0

嘗試以下操作:

  1. 創建一個文件/etc/nginx/upstream.conf

    server 10.0.0.2:8888; 
    server 10.0.0.3:8888; 
    server 10.0.0.4:8888; 
    
  2. 更改你的配置到:

    upstream app1 { 
        include /etc/nginx/upstream.conf; 
    } 
    
    server { 
        listen 80; 
    
        location /app1/ { 
        rewrite ^/app1^/ /$1 break; 
        proxy_pass http://app1; 
        } 
    } 
    
+0

感謝您的回答。 我檢查了這個變體,但我肯定需要將所有上游配置保存在單獨的文件中 - 這樣我可以通過重命名此文件來禁用此配置。 但似乎這是不可能的,所以我會去與包含指令。 –

0

upsteam部分需求無論如何,你需要在http塊中,它位於你的nginx.conf/default.conf中。
對於剛剛位置塊,你pobably可以使用:

default.conf

http { 
... 
    upstream app1 { 
     server 10.0.0.2:8888; 
     server 10.0.0.3:8888; 
     server 10.0.0.4:8888; 
    } 
... 
server { 
    listen  80; 
    server_name server.com; 

    include /path/to/app1.conf; 

    location/{ 
     root /www; 
     index index.html; 
    } 
... 
include /etc/nginx/conf.d/*; 
... 
} 

app1.conf

location /app1/ { 
    rewrite ^/app1^/ /$1 break; 
    proxy_pass http://app1; 
} 

編輯在默認情況下,include的路徑。 CONF。

編輯:
其實我在這裏犯了一個錯誤。 nginx的指令是分層的。在文檔中,您可以找到哪些地方可以使用哪個塊。 server塊需要位於http塊中。 location塊可以在serverlocation塊中。
根據您所在的塊,您可以使用include在該特定上下文中導入塊。
因此,在server塊中使用include可以包含應用程序特定的location塊,但不包括server塊。這是因爲server塊只能駐留在http塊中。
我希望這有助於澄清你的情況。

EDIT2:
從您的評論我剛纔看到的是,在重寫正則表達式也許是錯誤的。

app1.conf

location /app1/ { 
    rewrite ^/[^\/]+)(/.*) $1 break; 
    proxy_pass http://app1; 
} 
+0

重寫將從原始url/app1/some/more /中刪除/ app1 /。如果你不想要切斷任何東西,你應該刪除它。 – unNamed

+0

謝謝,我剛剛檢查過這個。當我有app1.conf與 位置/ app1/{0}改寫^/app1 ^// $ 1 break; proxy_pass http:// app1; } 我不能nginx的重新啓動時,收到錯誤: /etc/init.d/nginx重啓 [....]重新啓動的nginx(經由systemctl):nginx.serviceJob用於nginx.service失敗,因爲控制處理退出並顯示錯誤代碼。有關詳細信息,請參閱「systemctl status nginx.service」和「journalctl -xe」。 失敗! 和error.log中: 2017年3月3日15:29:05 [EMERG] 21787#0 「位置」 指令,在這裏不允許使用在/etc/nginx/app1.conf:1 –

+0

UPD: 我已經解決了這個問題 - 需要將app1.conf重命名爲app1(不帶.conf) –