问题: Nginx不会根据我在单独的配置文件中定义的规则来路由流量,只显示默认的404响应。
上下文: 我有一个用Go编写的小型中间件应用程序,它提供了对GET请求的简单响应。该应用程序部署在端口8080上:
$ curl localhost:8080
ok
我希望编写一个Nginx配置,允许我将来自 / api 的呼叫路由到 localhost:8080 ,这样我就可以执行以下操作
$ curl localhost/api
ok
为实现这一目标,我编写了以下配置:
的/ etc / nginx的/位点可用的/定制的nginx规则
server {
listen 80;
location /api {
proxy_pass http://localhost:8080;
}
}
我还在 / etc / nginx / sites-enabled / 中为上述文件创建了一个软链接
$ ls -l /etc/nginx/sites-enabled
total 0
lrwxrwxrwx 1 root root 34 Jan 19 16:42 default -> /etc/nginx/sites-available/default
lrwxrwxrwx 1 root root 32 Feb 20 14:56 custom-nginx-rules -> /etc/nginx/sites-available/custom-nginx-rules
其余的设置是vanilla Nginx,没有任何改变。 尽管设置很简单,但在拨打以下电话时我收到了404:
$ curl localhost/api
<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.10.3</center>
</body>
</html>
其他信息:以下是我系统上安装的nginx软件包(在raspberry pi上运行)
$ dpkg -l | grep nginx
ii libnginx-mod-http-auth-pam 1.10.3-1+deb9u1 armhf PAM authentication module for Nginx
ii libnginx-mod-http-dav-ext 1.10.3-1+deb9u1 armhf WebDAV missing commands support for Nginx
ii libnginx-mod-http-echo 1.10.3-1+deb9u1 armhf Bring echo and more shell style goodies to Nginx
ii libnginx-mod-http-geoip 1.10.3-1+deb9u1 armhf GeoIP HTTP module for Nginx
ii libnginx-mod-http-image-filter 1.10.3-1+deb9u1 armhf HTTP image filter module for Nginx
ii libnginx-mod-http-subs-filter 1.10.3-1+deb9u1 armhf Substitution filter module for Nginx
ii libnginx-mod-http-upstream-fair 1.10.3-1+deb9u1 armhf Nginx Upstream Fair Proxy Load Balancer
ii libnginx-mod-http-xslt-filter 1.10.3-1+deb9u1 armhf XSLT Transformation module for Nginx
ii libnginx-mod-mail 1.10.3-1+deb9u1 armhf Mail module for Nginx
ii libnginx-mod-stream 1.10.3-1+deb9u1 armhf Stream module for Nginx
ii nginx 1.10.3-1+deb9u1 all small, powerful, scalable web/proxy server
ii nginx-common 1.10.3-1+deb9u1 all small, powerful, scalable web/proxy server - common files
ii nginx-full 1.10.3-1+deb9u1 armhf nginx web/proxy server (standard version)
我还要求此设置独立于任何主机或服务器名称。无论主机如何,它都应该进行路由。
答案 0 :(得分:0)
如果没有看到您的完整配置,似乎可能是默认的nginx server
块正在接受请求,而不是您的。您可以尝试通过将listen行更改为:
listen 80 default_server;
您还可以通过添加server_name
并使用卷曲来确认是这种情况:
server_name api.example.com;
然后:
curl -H "Host: api.example.com" http://localhost/api
如果可行,问题肯定是default_server处理。
来自NGINX docs on server selection:
在此配置中,nginx仅测试请求的标头字段“Host”,以确定请求应路由到哪个服务器。如果其值与任何服务器名称都不匹配,或者请求根本不包含此标头字段,则nginx会将请求路由到此端口的默认服务器。在上面的配置中,默认服务器是第一个 - 这是nginx的标准默认行为。它还可以使用listen指令中的default_server参数显式设置哪个服务器应该是默认的: