2014-12-02 44 views
5

我的问题类似于Nginx Relative URL to Absolute Rewrite Rule? - 但有一个额外的转折。用nginx代理相关网址

我作为代理服务器,代理了多个应用,类似于这样(简化)配置nginx的:

server { 
    listen 80; 
    server_name example.com; 

    location /app1 { 
    proxy_pass http://app1.com; 
    } 
    location /app2 { 
    proxy_pass http://app2.com; 
    } 
} 

这工作得很好,但在其他问题,这些应用程序(app1app2)使用相关网址,例如/css/foo.css/js/bar.js。此外,要求所有应用程序更改为类似/app1/css/foo.css的东西也是一个大问题。

nginx是否可以智能地找出哪个应用程序应该处理请求? FTR,用户可以像这样访问这些应用程序:

http://example.com/app1/fooactionhttp://example.com/app2/baraction

如果很重要,所有应用程序都是基于Java/Tomcat的应用程序。

TIA!

+0

你能否澄清一点点,你要实现的目标是什么?你想要传递请求“/css/foo.css”到app1和“/js/bar.js”到app2吗? – danielgpm 2014-12-04 00:17:26

+0

是的。如果app1请求/css/foo.css,则应将其代理到app1.com/css/foo.css。如果app2请求/js/bar.js,则应将其代理到app2.com/js/bar.js。 – ragebiswas 2014-12-04 06:18:58

回答

7

根据您的更新评论; 如果上游后台发送Referer标头,你可以做这样的事情:

location ~* ^/(css|js)/.+\.(css|js)$ {    
     #checking if referer is from app1    
     if ($http_referer ~ "^.*/app1"){ 
      return 417; 
     }  

     #checking if referer is from app2 
     if ($http_referer ~ "^.*/app2"){ 
      return 418; 
     }  
    } 
    error_page 417 /app1$request_uri; 
    error_page 418 /app2$request_uri; 


    location /app1 {   
     proxy_pass http://app1.com; 
    } 

    location /app2 { 
     proxy_pass http://app2.com; 
    } 

例如,如果在app2.com后端,要求这样的test.css:

curl 'http://example.com/css/test.css' -H 'Referer: http://app2.com/app2/some/api' 

请求这里的土地:

/app2/css/test.css 
+1

我不认为你清楚地得到了我的问题。如果app1请求'/ css/foo.css',则它应该重定向到'http:// app1.com/css/foo.css'。但是,如果app2请求'/ css/foo.css',它应该转到'http:// app2.com/css/foo.css' – ragebiswas 2014-12-10 10:52:09

+0

,那么app1和app2在请求中是如何标识的?通过用户代理?头(引荐?)或请求参数?请提供更多详细信息... – danielgpm 2014-12-10 14:37:58

+1

对不起,如果我不清楚。 App1由位置标识。所以用户可以键入'example.com/app1/fooservice'。但app1的下游应用程序使用资源的相对URL,例如'/ css/bar.css'和NOT'/ app1/css/bar.css'。问题现在清楚了吗? FWIW一个来自nginx的解决方案在这里可能是不可能的。 – ragebiswas 2014-12-12 07:10:59