使用nginx作为反向代理到IIS服务器

18

我在同一台IIS服务器上运行多个ASP.NET应用程序,每个应用程序都有不同的端口。

我在同一台服务器上安装了nginx,这样我的客户端只需使用80端口即可访问所有应用程序。

Nginx在80端口正常运行。我的各个ASP.NET应用程序也在运行。

我在nginx配置文件中进行了这些更改。

    location /students/ {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:84;
    }
    location /registration/ {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:82;
    }

然后我重新启动了nginx,并在浏览器中输入了网址http://127.0.0.1/students/。Nginx返回了一个404错误页面。

我没有对配置文件做出其他更改。

我做错了什么?


那个配置看起来完全正确;我们在我的工作中有一个非常类似的配置,使用proxy_pass,在location块内部,没有URI部分,将请求传递给不同的服务器,URI保持不变。您能够验证Nginx是否进入了该location块吗? - ThrawnCA
3个回答

16
我认为你遇到的问题与URL路径的开头有关。如果URL http://120.0.0.1:84/students/ 返回页面而不是404错误,那么您需要在代理设置中加上结尾的斜杠/。如果您希望使用http://127.0.0.1:80/students/访问http://127.0.0.1/的页面,nginx将不会根据该配置自动转换路径,而是直接在代理服务器上查找相同路径。因此,请在proxy_pass指令中添加/
location /students/ {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;
    proxy_pass http://127.0.0.1:84/;
}
这是nginx配置文件中一个微妙但重要的坑!如果你没有包含反斜杠,http://127.0.0.1:84将会被视为服务器位置。如果你加上反斜杠,它将被视为URL,并且会替换代理URL中“location”部分之前的所有内容。

如果我浏览http://127.0.0.1:84/students, 我会获得我的页面,因为IIS正在监听84端口。我想要的是,如果我浏览http://127.0.0.1/students,那么nginx应该将url重写为http://127.0.0.1:84。这在nginx中可能吗? - Shuaib
我仍然收到由Nginx提供的404页面。 - Shuaib
我要前往127.0.0.1/students。我不想去127.0.0.1:84/students... IIS可以提供服务,我不需要nginx @jwg。 - Shuaib
你是要访问 http://127.0.0.1/students 还是 http://127.0.0.1/students/?抱歉,StackOverflow移除了URL末尾的斜杠,这就是问题的关键所在! - jwg
nginx能否将http://127.0.0.1/students/Login.aspx转换为http://127.0.0.1:84/students/Login.aspx,@jwg? - Shuaib
显示剩余4条评论

1
如果你想将IIS 127.0.0.1:84/students转换为nginx 127.0.0.1/students,请尝试以下代码...
location /students {
   proxy_set_header X-Real-IP  $remote_addr;
   proxy_set_header X-Forwarded-For $remote_addr;
   proxy_set_header Host $host;
   proxy_pass http://127.0.0.1:84/students;
 }
location /registration {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;
    proxy_pass http://127.0.0.1:82/registration;
}

-4

尝试使用这个指令

 upstream http://localhost {
     server 127.0.0.1:84;
 }

和第二个使用相同的代码块


Nginx 给我报错... upstream 在这里不允许。 - Shuaib
请在你的回答中添加一些解释! - ρss

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接