如何截取nginx的URL

huangapple go评论64阅读模式
英文:

How to cut nginx url

问题

我正在使用nginx来代理请求到三个服务。我需要截取请求的URL并将其代理到已更改的URL的服务上。
这里是一个示例:
example.com/blabla/admin/dashboard/... -> 代理到
localhost:8080/admin/dashboard/...
我想出于安全原因这样做,当然我可以创建子域名(blablabla.example.com/admin/dashboard),但我认为URL比子域名更安全。

我尝试了以下配置,但它只是使用原始URL进行代理:

upstream web1 {
    server site1:8080;
}

upstream web3 {
    server site3:8080;
}

upstream web2 {
    server site2:8080;
}

server {
    listen       80;
    listen  [::]:80;
    # server_name  localhost;

    location /balaboba {
        proxy_pass http://web1$uri;
    }

    location /catsruletheworld {
        proxy_pass http://web2$uri;
    }

    location /lolkek {
        proxy_pass http://web3$uri;
    }
}
英文:

I am using nginx to proxy requests to three services. I need to cut request url and proxy to services with changed url.
Here example:
example.com/blabla/admin/dashboard/... -> proxy to
localhost:8080/admin/dashboard/...
I want to do it for safety reasons, of course I can make subdomain (blablabla.example.com/admin/dashboard), but I think url is safer
than subdomain.

I am tried this configuration, But it just proxy with original url:

upstream web1 {  
    server site1:8080;  
}  
  
upstream web3 {  
    server site3:8080;  
}  
  
upstream web2 {  
    server site2:8080;  
}  
  
server {  
    listen       80;  
    listen  [::]:80;  
    # server_name  localhost;  

    location /balaboba {  
        proxy_pass http://web1$uri;  
    }  
  
    location /catsruletheworld {  
        proxy_pass http://web2$uri;  
    }  
  
    location /lolkek {  
        proxy_pass http://web3$uri;  
    }  
}  

答案1

得分: 0

$uri 是原始的URL,所以你需要在proxy_pass语句中明确地发送它。

在前缀location中使用proxy_pass可以自动实现你想要做的事情。只需在locationproxy_pass语句后面加上斜杠/来替代前缀为/。参见proxy_pass文档。

例如:

location /foo/ {
    proxy_pass http://service/;
}

在上述示例中,URL http://example.com/foo/bar 将被传递到 http://service/bar

这仅在服务端表现良好且不生成打破所施加前缀的绝对链接时才有效。在这种情况下,子域方法可能会更安全。

英文:

$uri is the original URL, so you are explicitly sending it in your proxy_pass statements.

proxy_pass within a prefix location can automatically achieve what you are trying to do. Simply use a trailing / on both the location and proxy_pass statements to substitute the prefix for /. See proxy_pass documentation.

For example:

location /foo/ {
    proxy_pass http://service/;
}

In the above, the URL http://example.com/foo/bar will be passed to http://service/bar

This only works if the service is well behaved and does not generate absolute links that break out of the imposed prefix. In which case the subdomain approach may be safer after all.

huangapple
  • 本文由 发表于 2023年6月15日 17:53:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76481305.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定