2016-10-18 45 views
0

我試圖使用nginx爲nodejs應用程序設置反向代理。我的節點應用程序當前運行在example.com服務器的端口8005上。運行該應用程序並轉到example.com:8005,該應用程序可以正常工作。但是,當我嘗試設置nginx時,我的應用程序似乎首先通過訪問example.com/test/工作,但是當我嘗試發佈或獲取請求時,請求希望使用example.com:8005 url,最後我一個交叉原點錯誤,CORS。我想請求url反映nginx網址,但我沒有運氣去那裏。以下是我的nginx default.conf文件。nginx反向代理髮布/獲取請求失敗

server { 
    listen  80; 
    server_name example; 

    location/{ 
     root /usr/share/nginx/html; 
     index index.html index.htm; 
    } 

    error_page 500 502 503 504 /50x.html; 
    location = /50x.html { 
     root /usr/share/nginx/html; 
    } 

    location /test/ { 
     proxy_pass http://localhost:8005/; 
     proxy_http_version 1.1; 
     proxy_set_header Upgrade $http_upgrade; 
     proxy_set_header Connection 'upgrade'; 
     proxy_set_header Host $host; 
     proxy_cache_bypass $http_upgrade; 
    } 
} 
+0

是您的文章/獲取前綴請求 '/測試/'(被他們落下到/測試/定位塊)? – roger

+0

@roger沒有我的帖子沒有任何前綴 – Woodsy

+0

如果是這樣的話,我猜他們正在被'/'位置塊(當前正在服務靜態文件)捕獲。如果你想讓它們在你的節點進程中被使用,你需要確保這些請求使用proxy_pass http:// localhost:8005/ – roger

回答

1

有一些方法可以告訴nginx你正在使用的任何應用程序。

因此,要麼你可以前綴所有的apis與說測試(location /test/api_uri),然後捕獲所有的URL前綴/測試和proxy_pass他們節點,或者如果你有一些特定的模式,你可以用正則表達式來捕獲這個模式,就像所有的app1 apis都包含app1的某個地方,然後使用location ~ /.*app1.* {} location ~ /.*app2.*來捕獲這些url,確保你保持位置的order

演示代碼:

server { 
    ... 
    location /test { 
     proxy_pass http://localhost:8005/; #app1 
     proxy_http_version 1.1; 
     proxy_set_header Upgrade $http_upgrade; 
     proxy_set_header Connection 'upgrade'; 
     proxy_set_header Host $host; 
     proxy_cache_bypass $http_upgrade; 
    } 
    location /test2 { 
     proxy_pass http://localhost:8006/; #app2 
     proxy_http_version 1.1; 
     proxy_set_header Upgrade $http_upgrade; 
     proxy_set_header Connection 'upgrade'; 
     proxy_set_header Host $host; 
     proxy_cache_bypass $http_upgrade; 
    } 
    ... 
} 

其他演示了正則表達式,

server { 
    ... 
    location ~ /.*app1.* { 
     proxy_pass http://localhost:8005/; #app1 
     proxy_http_version 1.1; 
     proxy_set_header Upgrade $http_upgrade; 
     proxy_set_header Connection 'upgrade'; 
     proxy_set_header Host $host; 
     proxy_cache_bypass $http_upgrade; 
    } 
    location ~ /.*app2.* { 
     proxy_pass http://localhost:8006/; #app2 
     proxy_http_version 1.1; 
     proxy_set_header Upgrade $http_upgrade; 
     proxy_set_header Connection 'upgrade'; 
     proxy_set_header Host $host; 
     proxy_cache_bypass $http_upgrade; 
    } 
    ... 
}