2016-10-18 43 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; 
    } 
    ... 
}