如何在保留用户input的URL的同时使用Nginx来重写和proxy_pass

我是一个初学者的Nginx用户试图代理以下内容:

http://subdomain.example.com/mypage/login TO http://some_ip_address/login 

(不只是/login – 该网站也有其他上下文,例如/静态,/ API等)

虽然我可以在function上做到这一点,但用户可以在他们的浏览器中看到http://some_ip_address ,这是我想避免的。

该configuration看起来像这样:

 worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 3; server { server_name this_server_ip; location /mypage/ { proxy_pass http://some_ip_address; rewrite ^/mypage/(.*)$ http://some_ip_address/$1 last; } location / { root /var/local/directory/; } } } 

为了解决这个问题,我尝试了下面的组合:

  • proxy_pass http://some_ip_address/; (即用斜线)
  • proxy_set_header Host $host;
  • rewrite ^/mypage/(.*)$ /$1 last;

但是,我要么获得404的或提供在http://subdomain.example.com托pipe的网页,即rewrite作品,但proxy_pass不。

在serverfault上有几个类似的问题,但不幸的是,似乎没有一个能够解决这个问题。 例子是这一个 那个 。

任何build议将非常感激,谢谢。

您将指定this_server_ip作为此虚拟主机的主机名。 这意味着此虚拟主机不用于具有域名的任何请求,但您的nginx默认虚拟服务器用于请求http://subdomain.example.com/

您需要将您的server_name更改为subdomain.example.com ,或将default_server添加到此server块上的listen指令,并将其从nginx默认configuration中移除。

编辑:尝试这个虚拟主机configuration:

 server { server_name subdomain.example.com; location ~ /(mypage|static/api)/ { proxy_pass http://some_ip_address/$1/; } location / { root /var/local/directory/; } } 

也就是说,根本不需要rewrite语句,因为您正在将请求代理到另一台服务器。