2012-10-13 77 views
2

我想重定向不同的URI請求到不同的EC2容器,我一直使用nginx多年來作爲一個catchall反向代理到Apache,但現在我想有一些在nginx級別重寫。nginx - 無法找出位置重寫

這裏就是我試圖完成:

server { 
    listen  80; 
    server_name _; 

    gzip    on; 
    gzip_static  on; 
    gzip_buffers  16 8k; 
    gzip_comp_level 9; 
    gzip_http_version 1.0; 
    gzip_min_length 0; 
    gzip_types  text/plain text/css application/x-javascript; 
    gzip_vary   on; 

    location/{ 
     # catch the following URI's including homepage: /contact.html, /terms.html,/
     proxy_set_header Host $host; 
     proxy_set_header X-Real-IP $remote_addr; 
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
     proxy_read_timeout 240; 
     proxy_connect_timeout 240; 
     proxy_send_timeout 240; 

     send_timeout 240; 
     proxy_pass http://servers_static; 
    } 

    location/{ 
     # catch everything not matched above 
     proxy_set_header Host $host; 
     proxy_set_header X-Real-IP $remote_addr; 
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
     proxy_read_timeout 240; 
     proxy_connect_timeout 240; 
     proxy_send_timeout 240; 

     send_timeout 240; 
     proxy_pass http://servers_dynamic; 
    } 
} 

我敢肯定,這只是一個簡單的正則表達式的問題,但我永遠無法理解的東西。有人可以幫我嗎?

回答

2

創建一個文件,與普通代理服務器設置在/ etc/nginx的/ EC2 :

proxy_set_header Host $host; 
proxy_set_header X-Real-IP $remote_addr; 
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
proxy_read_timeout 240; 
proxy_connect_timeout 240; 
proxy_send_timeout 240; 
send_timeout 240; 

你的主要配置就變成了:

server { 
    listen  80; 
    server_name _; 

    #gzip settings cut for brevity, add them back in  

    # static content 
    location =/{include /etc/nginx/EC2; proxy_pass http://servers_static;} 
    location = /contact.html {include /etc/nginx/EC2; proxy_pass http://servers_static;} 
    location = /terms.html {include /etc/nginx/EC2; proxy_pass http://servers_static;} 

    # dynamic content 
    location/{ include /etc/nginx/EC2; proxy_pass http://servers_dynamic; } 
} 

你可能還結合位置爲html的靜態內容頁,像這樣:

location ~ (contact|terms).html { 
    include /etc/nginx/EC2; proxy_pass http://servers_static;} 

它可能會更有效有精確匹配的位置,只要你不必多由此產生的重複不應該使配置難以執行

+0

我在下面發佈的答案實際上產生了一些其他問題,另一方面您的解決方案解決了我的問題!謝謝 – Joe

0

看看try_files。它會先後嘗試你給它的路徑。在這個例子中,將返回/var/www/sites/foo/current/public/$uri的任何靜態文件,只有在沒有靜態文件存在的情況下才將請求路由到應用程序。

upstream app { 
    server unix:/tmp/.sock_my_app; 
} 

server { 
    # path for static files 
    root /var/www/sites/foo/current/public; 

    # Prefer to serve static files directly from nginx to avoid unnecessary 
    # requests to the application server. 
    try_files $uri/index.html $uri.html $uri @app; 

    location @app { 
    proxy_set_header Host $http_host; 
    proxy_set_header X-Real-IP $remote_addr; 
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 

    # timeouts 

    # reverse proxy to an upstream 
    proxy_pass http://app; 
    } 
} 
+0

這是一個好主意,但不幸的是,nginx服務器位於ec2實例上,靜態/動態內容位於單獨的實例中,因此無法查詢本地文件系統。 – Joe