Config Nginx For Security
Tags: programming, dveops, nginx
Published: 2020-11-17 05:01:40

---
title: Config Nginx For Security
published: true
date: 2020-11-16 22:52:00 UTC
tags: Programming, DveOps, Nginx
canonical_url: http://coderscat.com/config-nginx-for-security/
---

[Orignal Post](http://coderscat.com/config-nginx-for-security/)

When I was in the security group, we found many programmers don't know how to handle, or don't have the awareness of Nginx's security. We found many exploitations or cases of sensitive data was pulled from web servers by attackers.

Here I will list some configurations for Nginx's Security. Please do adjustments to these configurations according to your actual requirements.



![Nginx Logo - LogoDix](http://coderscat.com/images/1638974.png)

## Forbidden any sensitive request path 

Many source codes are using Git as version control tools. The directory `.git` will contains all the metadata of codebase, including some secrets, etc. Expose it to the public will make your codebase downable for attackers:

<img src="http://coderscat.com/images/image-20201116125232230.png" width="50%">

So we need to disable the `.git` related request routes.

```nginx 
location ~ /\.git {
  deny all;
}
## Disable .htaccess and other hidden files
location ~ /\.(?!well-known).* {
    deny all;
    access_log off;
    log_not_found off;
}
```

## Forbidden unnecessary HTTP request methods 

The most commonly used HTTP request methods are GET, POST, HEAD. We should return 444 for any other unused methods.

```nginx
## Only allow these request methods ##
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
         return 444;
}
## Do not accept DELETE, SEARCH, and other methods ##
```

## Add request rate limiting

[Rate limiting](https://www.nginx.com/blog/rate-limiting-nginx/) will block many malicious requests, and it is also a frequently used tool to defend against network and application-level **DDoS attacks** against websites.

We can add the maximum request limit for a single IP.

```nginx
limit_req_zone $binary_remote_addr zone=ip:10m rate=5r/s;

server {
    listen 80;
    location / {
        limit_req zone=ip burst=12 delay=8;
        proxy_pass http://website;
    }
}
```

## Add HTTPS for your service

If you are deploying a non-company project,  [Let's encrypt](https://letsencrypt.org/) will be enough for personal usage. And remember to redirect all non-HTTPS requests to HTTPS with 301. 

```nginx
server {
    listen               80;
    listen               443 ssl;
    server_name          www.coderscat.com;
    ssl_certificate      /etc/letsencrypt/live/coderscat.com/fullchain.pem;
    ssl_certificate_key  /etc/letsencrypt/live/coderscat.com/privkey.pem;
    return 301 https://coderscat.com$request_uri;
}

server {
    listen 80;
    listen 443 ssl http2;
    server_name coderscat.com;

    # ssl on;
    ssl_certificate       /etc/letsencrypt/live/coderscat.com/fullchain.pem;
    ssl_certificate_key  /etc/letsencrypt/live/coderscat.com/privkey.pem;

    ssl_protocols        TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers          ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
    ssl_prefer_server_ciphers  on;
    ssl_session_cache    shared:SSL:10m;
    ssl_session_timeout  10m;
}
```

## Enable SELinux

`SELiunux` stands for Security-Enhanced Linux, it is a Linux kernel security module that provides a mechanism for supporting access control security policies, including mandatory access controls (MAC).  It can prevent several attacks before your system being hacked.

Install it on Ubuntu: 

```shell
$ sudo apt install policycoreutils selinux-utils selinux-basics
$ sudo selinux-activate
$ sudo selinux-config-enforcing  (Then reboot system)
$ sudo sestatus (query the status of SELinux)
```

### Clickjacking Attack

[Clickjacking attack](https://www.imperva.com/learn/application-security/clickjacking/)  will cause users to unwittingly download malware, visit malicious web pages, provide credentials or sensitive information.

We can inject `X-FRAME-OPTIONS` in HTTP Header to prevent a clickjacking attack(Even this can be bypassed in some ways). This is achieved by adding below in `nginx.conf` file

```nginx
add_header X-Frame-Options "SAMEORIGIN";
```

Above header will instruct a browser to load the resources ONLY from the same origin.

### X-XSS Protection

Inject HTTP Header with X-XSS protection to mitigate Cross-Site scripting attack. Modify `nginx.conf` file to add the following

```nginx
add_header X-XSS-Protection "1; mode=block";
```

Save the configuration file and restart Nginx. You can use the [Headers Test](https://gf.dev/http-headers-test) tool to verify after implementation.

You may also be interested in implementing OWASP recommended secure headers which are explained [here](https://geekflare.com/http-header-implementation/).


## References

[Mastering NGINX Second Edition](https://amzn.to/3f21Uwd) is an excellent reference book for the introduction of Nginx.