如何让nginx返回404,除非请求一个特定的域名?

我有一个nginx服务器,我想返回404时,请求anything除了anythingwwwmypythonapp1mypythonapp2

我在/etc/nginx/sites-enabled创build了一个00-noredirect文件:

 server { listen 80; listen 443 ssl; server_name _; return 404; } 

不幸的是,一切都redirect到mypythonapp1

其他服务器块如下:

 server { listen mypythonapp1.mydomain.com:80; server_name mypythonapp1.mydomain.com; (...) listen mypythonapp1.mydomain.com:443 ssl; # managed by Certbot (...) } 

我认为这可能与我/etc/nginx/sites-enabled/mypythonapp1 ,即使我不确定:

 (...) if ($scheme != "https") { return 301 https://$host$request_uri; } # managed by Certbot (...) 

有什么我必须添加到00-noredirect避免这种不需​​要的行为?

编辑:按照@Tim的要求,这里是我的 – 最完整的nginxconfiguration:

 server { listen 80; server_name mypythonapp1.mydomain.com; disable_symlinks off; location /static { alias /var/www/mypythonapp/mypythonapp/mypythonapp/static; } location / { try_files $uri @yourapplication; } location @yourapplication { include uwsgi_params; uwsgi_pass unix:/var/run/uwsgi/app/mypythonapp1/socket; } listen 443 ssl; # managed by Certbot # some ssl magic here if ($scheme != "https") { return 301 https://$host$request_uri; } # managed by Certbot } server { listen 80; server_name mypythonapp2.mydomain.com; disable_symlinks off; location /static { alias /var/www/mypythonapp/mypythonapp/mypythonapp/static; } location / { try_files $uri @yourapplication; } location @yourapplication { include uwsgi_params; uwsgi_pass unix:/var/run/uwsgi/app/mypythonapp2/socket; } listen 443 ssl; # managed by Certbot # some ssl magic here if ($scheme != "https") { return 301 https://$host$request_uri; } # managed by Certbot } server { listen 80; server_name www.mydomain.com mydomain.com; root /home/me/mystaticwebsite/; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; } listen 443 ssl; # managed by Certbot # some ssl magic here if ($scheme != "https") { return 301 https://$host$uri; } # managed by Certbot } server { listen 80 default_server; server_name _; return 444; } # this last bit I commented out because it broke everything... #server { # listen 443 default_server; # # server_name _; # # return 444; #} 

编辑2:检查error.log (为什么我以前不这样做…)我意识到,最后一部分“打破了一切”,因为no "ssl_certificate" is defined in server listening on SSL port while SSL handshaking 。 我最终复制了certbot添加到其他域的ssl_certificatessl_certificate_key行。 现在我在请求anything.mydomain.com时仍然有一个证书警告,但至less如果我绕过它,我不会访问mypythonapp1 ,这是我真正想要的。

通过您要服务的域名创build指定server_name的服务器块。 接下来创build一个默认服务器来处理所有其他的 你不应该返回404,返回一个更合适的代码。

 server { # These can be in individual servers if you like server_name anything.mydomain.com www.mydomain.com etc.mydomain.com # add configuration } # This just prevents Nginx picking a random default server if it doesn't know which # server block to send a request to server { listen 80 default_server; server_name _; return 444; # "Connection closed without response" }