If I already have a bunch of virtualhosts, how can I create a virtual host to handle requests that don't match any of the virtualhosts? (i.e. access by IP, another domain linking to IP, .etc .etc)
4 Answers
server_name _; and default_server on the listen configuration are what you are looking for.
Example:
server {
listen 80 default_server;
server_name _;
root /var/www/default; (or wherever)
}
- 856
- 7
- 4
-
1And for the https case: `listen 443 ssl default_server;` – James T Snell Sep 15 '15 at 16:34
-
When I enable this, my `owncloud 9` won't respond. Why? Owncloud VHOST has a server_name and is no default_server. – Powerriegel Jul 16 '16 at 07:56
-
I don't use `80` only 443 is open. – Powerriegel Jul 16 '16 at 08:06
-
If I add this, my other config snippets in /etc/nginx/sites-enabled/ are ignored. all domains go to `/var/www/default` in this case. How do I have to order the snippets? – rubo77 Aug 11 '18 at 14:57
-
I can create a vhos to postgresql connections? – Erlon Charles Sep 14 '18 at 14:35
-
If you just want to sinkhole people, you can just do a `return 404` as your last call. – mlissner Nov 07 '20 at 16:19
If you use SSL, then you need some extra plumbing for a default_server - certificate and key (that can be self-signed).
server {
server_name _;
listen 80 default_server;
listen 443 ssl default_server;
ssl_certificate <path to cert>;
ssl_certificate_key <path to key>;
return 404; # or whatever
}
Nginx will try to accept SSL connection on an IP/port-matching default_server. If such server is missing cert/key, nginx will drop the connection. It won't try other servers. So don't forget cert/key.
- 669
- 8
- 6
-
1Important note about the SSL certificate! If the certificate is missing, the whole nginx server will not run (even though `nginx -t` says "ok") – Philipp Mar 11 '19 at 22:20
server {
listen 80 default_server;
listen 443 ssl default_server;
listen [::]:80 default_server;
listen [::]:443 ssl default_server;
server_name _;
root /path/to/default;
}
The entries are for port 80 (HTTP), port 443 (HTTPS), port 80 IPv6, and port 443 IPv6, respectively.
You could consider adding log_not_found off;
to avoid adding a log entry for the page not being found.
- 783
- 1
- 6
- 17
In the event that you have listen
directives with explicit IPs listed, you will need to also include these same IPs in your default block's listen directive.
server {
listen 80 default_server;
listen 10.0.0.10:80 default_server;
server_name _;
}
server {
listen 10.0.0.10:80;
server_name foo.example.com;
}
Without the listen 10.0.0.10:80 default_server
directive in the default block, foo.example.com
would be served for http://10.0.0.10
even if 10.0.0.10
is your default IP address.
- 249
- 2
- 9