Nginx default server configuration

Adrien | 08 Jul 2019

Setup a catch-all, wildcard default server on Nginx reverse proxy.

Image by Pete Linforth from Pixabay

Nginx reverse-proxy

Nginx is the solution when it comes to reverse proxy. It has a wide range of features for security and performances. Today, we will setup a catch-all default server configuration.

Why a catch-all default server?

  • Protect your website(s) against unwanted requests.
  • Prevent passing requests that doesn't belongs to your application.
  • Reduce junk in your webserver logs.
  • Avoid misconfigured domain to point on a wrong webserver.

How to configure Nginx default server?

By default, Nginx provides a file /etc/nginx/site-available/default that you can modify like this:

# /etc/nginx/sites-available/default

server {
    server_name default_server;

    root /var/www/html/;
    listen 80;

    location / {
       deny all;
    }
}

Above configuration will catch all requests that don't match other servers. It will return a 403 Forbidden (deny all).

However, it is very often that attackers and bad bots use https requests (port 443). As Nginx default server is listening on port 80 only, we can still access your application webserver! Try it by yourself using curl with unsecured option -k:

$ curl -k https://<your.website.ip>

In order to catch https requests, you must create a self-signed certificate as Nginx need it to enable ssl on port 443.

  1. Create a self-signed certificate using openssl:
$ sudo mkdir /etc/nginx/ssl/
$ sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt
  1. Modify /etc/nginx/sites-available/default file like below:
# /etc/nginx/sites-available/default

# catch all requests on port 80
server {
    server_name default_server;
    root /var/www/html/;
    listen 80;

    access_log /var/log/nginx/default.access.log;
    error_log /var/log/nginx/default.error.log;

    location / {
        deny all;
    }

}

# catch all requests on port 443 with ssl on
server {
    server_name default_server;
    root /var/www/html/;

    access_log /var/log/nginx/default.access.log;
    error_log /var/log/nginx/default.error.log;

    listen 443 ssl;
    ssl_certificate /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;

    location / {
        deny all;
    }
}
  1. Reload Nginx
$ sudo systemctl reload nginx

Conclusion

After this configuration done, your website junk logs will reduce considerably as most of basic attacks / bad crawlers will be filtered at the proxy level.

Send your comments on our Facebook and LinkedIn pages.

Related posts: