使用nginx代理相对URL

rag*_*was 8 proxy webserver reverse-proxy nginx

我的问题类似于Nginx相对URL到绝对重写规则? - 但附加扭曲.

我有nginx充当代理服务器,代理多个应用程序,类似于这个(简化)配置:

server {
  listen 80;
  server_name example.com;

  location /app1 {
    proxy_pass   http://app1.com;
  }
  location /app2 {
    proxy_pass http://app2.com;
  }
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,但在另一个问题中,这些应用程序(app1app2)使用相对URL,如/css/foo.css,或/js/bar.js.要求所有应用程序更改为类似的东西也是一个大问题/app1/css/foo.css.

是否有可能nginx智能地确定哪个应用程序应该处理请求?FTR,用户将访问这些应用程序,如下所示:

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

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

TIA!

dan*_*gpm 8

根据您的最新评论; 如果上游后端发送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;
    }
Run Code Online (Sandbox Code Playgroud)

例如,如果app2.com上的后端,请求test.css如下:

curl 'http://example.com/css/test.css' -H 'Referer: http://app2.com/app2/some/api'
Run Code Online (Sandbox Code Playgroud)

请求落在这里:

/app2/css/test.css 
Run Code Online (Sandbox Code Playgroud)

  • 我认为您不清楚我的问题。如果app1请求`/ css / foo.css`,则应重定向到`http:// app1.com / css / foo.css`。但是,如果app2请求`/ css / foo.css`,则应转到`http:// app2.com / css / foo.css` (2认同)