![当我声明多个 NGINX 服务器块时,为什么它们会互相影响?](https://linux22.com/image/786064/%E5%BD%93%E6%88%91%E5%A3%B0%E6%98%8E%E5%A4%9A%E4%B8%AA%20NGINX%20%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%9D%97%E6%97%B6%EF%BC%8C%E4%B8%BA%E4%BB%80%E4%B9%88%E5%AE%83%E4%BB%AC%E4%BC%9A%E4%BA%92%E7%9B%B8%E5%BD%B1%E5%93%8D%EF%BC%9F.png)
我有以下服务器块...
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
include snippets/self-signed.conf;
include snippets/ssl-params.conf;
server_name secondave.net www.secondave.net;
location / {
proxy_pass http://localhost:3000;
}
}
server {
listen 80;
listen [::]:80;
server_name _;
location / {
proxy_pass http://localhost:3000;
}
}
}
不过我希望它能起作用......
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
include snippets/self-signed.conf;
include snippets/ssl-params.conf;
server_name secondave.net www.secondave.net;
location / {
proxy_pass http://localhost:3000;
}
}
server {
listen 80;
listen [::]:80;
server_name _;
}
但如果我尝试这样做,反向代理将不再起作用。为什么两个地方都需要 proxy_pass?
这是我尝试在端口 80 块中调用没有 proxy_pass 的端点......
[ec2-user@... nginx]$ curl --insecure https://secondave.net
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
请注意Welcome to nginx!
,这不是代理站点所说的内容。当我再次添加它时,我再次看到了预期的站点...
[ec2-user@... nginx]$ sudo vi nginx.conf
[ec2-user@... nginx]$ sudo systemctl restart nginx
[ec2-user@... nginx]$ curl --insecure https://secondave.net
<!DOCTYPE html><html><head><meta charSet="utf-8"/><title>THEJa
这是使用 AWSLinux2023,我相信它是 selinux 的一部分,并且 nginx 是使用 yum 安装的。
附加信息
[ec2-user@... ~]$ cat /etc/nginx/nginx.conf
...
http {
...
server {
...
}
server {
listen 80;
listen [::]:80;
server_name secondave.net www.secondave.net;
return 404;
}
}
[ec2-user@... ~]$ sudo systemctl restart nginx
[ec2-user@... ~]$ curl --insecure https://secondave.net
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.22.1</center>
</body>
</html>
答案1
您的server
HTTP 块没有server_name
。因此它不处理请求,但请求被传递给 nginx default_server
,后者通常会显示您看到的页面。
您至少应该有这个端口80
:
server {
listen 80;
listen [::]:80;
server_name <hostname>;
return 404;
}
此配置将为所有失败的请求返回 HTTP 未找到错误代码。