# needed if your proxy destination specified with domain name instead of IP address
resolver 8.8.8.8;
location /home/ {
proxy_set_header Host HOST1;
# setup other proxied headers if needed
if ($http_referer ~ ^https?://dev.xyz.com/home) {
rewrite ^/home(/.*)$ HOME_PAGE$1 break;
proxy_pass https://HOST1:8080; # this can be specified by IP address
}
}
有了这样的配置请求your_domain.com/home/path/file
from dev.xyz.com/home/...
(但不是来自dev.xyz.com/any/other/path
!)将被代理到https://HOST1:8080/HOME_PAGE/path/file
。如果您使用域名而不是 IP 地址指定代理目标,则需要指定附加参数resolver http://nginx.org/en/docs/http/ngx_http_core_module.html#resolver在你的服务器配置中。您可以使用本地名称服务器(如果有),也可以使用外部名称服务器,例如 Google 公共 DNS (8.8.8.8) 或 ISP 为您提供的 DNS。无论如何,这样的配置会导致额外的 DNS 查找,因此如果可以的话,请使用 IP 地址指定您的代理目标。
Update
还有另一种方法可以做到这一点valid_referers http://nginx.org/en/docs/http/ngx_http_referer_module.html#valid_referers指示:
# needed if your proxy destination specified with domain name instead of IP address
resolver 8.8.8.8;
location /home/ {
proxy_set_header Host HOST1;
# setup other proxied headers if needed
valid_referers example.com/home;
if ($invalid_referer = "") {
rewrite ^/home(/.*)$ HOME_PAGE$1 break;
proxy_pass https://HOST1:8080; # this can be specified by IP address
}
}
更新@2020.11.11
除了这个答案以某种方式获得了 5 分之外,给定的解决方案的设计非常糟糕(在location
和嵌套的if
堵塞;此外,拥有一个if
使用除 nginx 之外的任何指令进行阻止重写模块 http://nginx.org/en/docs/http/ngx_http_rewrite_module.html如果可能的话应该避免)并且在早期的 nginx 版本上根本不起作用(当我看到我的一些早期答案时我想哭)。最初的OP问题是
逻辑应该如下所示,但有一些语法错误。
if ($http_origin ~ '^http?://(dev.xyz.com/home)') {
set $flag 'true';
}
if ($flag = 'true') {
location /home/ {
proxy_pass "https://HOST1:8080/HOME PAGE/";
}
}else{
Do Not proxy pass
}
目前尚不清楚是什么不代理通过方法。如果这意味着返回一些HTTP错误(例如HTTP 403 Forbidden),可以通过以下配置来完成:
location /home/ {
if ($http_referer !~ ^https?://dev.xyz.com/home) {
return 403;
}
rewrite ^/home(/.*)$ HOME_PAGE$1 break;
proxy_set_header Host HOST1;
# setup other proxied headers if needed
proxy_pass https://HOST1:8080; # this can be specified by IP address
}
If 不代理通过意味着在本地处理请求,解决方案更复杂:
map $http_referer $loc {
~^https?://dev.xyz.com/home loc_proxy;
default loc_local;
}
server {
...
location /home/ {
try_files /dev/null @$loc;
}
location @loc_proxy {
rewrite ^/home(/.*)$ HOME_PAGE$1 break;
proxy_set_header Host HOST1;
# setup other proxied headers if needed
proxy_pass https://HOST1:8080;
}
location @loc_local {
rewrite ^/home(/.*)$ HOME_PAGE$1 break;
root /path/to/required/page;
...
}
The try_files /dev/null @the_named_location;
技巧取自this https://serverfault.com/questions/908086/nginx-directly-send-from-location-to-another-named-location/965779#965779很好的答案。
然而,现在编辑后的OP的问题提出了不同的要求,这也可以通过map
指令帮助:
map $http_referer $environment {
~^https?://dev.xyz.com/home Environment1;
default Environment2;
}
server {
...
location /home/ {
rewrite ^/home(/.*)$ HOME_PAGE$1 break;
proxy_set_header Host $environment;
# setup other proxied headers if needed
proxy_pass https://$environment;
}