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 set up a catch-all default server configuration.
Why a catch-all default server?
- Protect your website(s) against unwanted requests.
- Prevent passing requests that don't belong to your application.
- Reduce junk in your web server logs.
- Avoid misconfigured domains to point to 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 {
listen 80 default_server;
server_name _;
root /var/www/html/;
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 needs it to enable ssl on port 443.
- 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
- Modify /etc/nginx/sites-available/default file like below:
# /etc/nginx/sites-available/default
# catch all requests on port 80
server {
listen 80 default_server;
server_name _;
root /var/www/html/;
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 _;
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;
}
}
- Reload Nginx
$ sudo systemctl reload nginx
Conclusion
After this configuration is done, your website junk logs will reduce considerably as most of the basic attacks/bad crawlers will be filtered at the proxy level.
Edit: Updated on 11-May-2020.