Nginx Hardening - Some Good Security Practices

As a start this article collects some hints on how to improve the general security of nginx web servers.

It does not cover SSL, PHP-FPM, or Reverse proxy configuration hardening etc... For this, please refer to the official documentation and to the references below.

Http level configuration - for all vhosts

## Silently block all undefined vhost access : that's a good start!
server {
        server_name _;
        return 444;

## Disable Nginx version number in error pages and Server header
server_tokens off;

## Socket settings : Set buffer size limitations
client_header_buffer_size   4k;
large_client_header_buffers 8 8k;
client_max_body_size 20m;
connection_pool_size 8192;
request_pool_size 8k;

## Add here all HTTP method allowed
map $request_method $bad_method {
        default 1;
        ~(?i)(GET|HEAD|POST) 0;

Server level configuration - to include in your vhost

## Deny access based on HTTP method
if ($bad_method = 1) {
        return 444;

location = /robots.txt  { access_log off; log_not_found off; }
location = /favicon.ico { access_log off; log_not_found off; }
## Disable access to hidden files
location ~ /\.          { access_log off; log_not_found off; deny all; }
location ~ ~$           { access_log off; log_not_found off; deny all; }

Some rulesets pretend to block most common exploits. You should not trust that because it does not block much... Moreover it will make your webserver slower as it makes intensive use of the "if" directive. "if is evil", prefer the "map" directive instead.

Nginx does not provide a solution to block common exploits, SQL injections or file injections. For this you should definitely install an IDS or a WAF like Naxsi. But first I would recommend to regularly patch your CMS, or whatever the software you installed behind your web frontends.