Secure Your Webserver with Nginx
Tags: security, webdev, tutorial, beginners
Published: 2023-02-12 16:51:30

In today's digital age, a secure web server is essential for protecting sensitive information and maintaining the integrity of your website. Hackers and cybercriminals are constantly finding new ways to exploit vulnerabilities in web servers, so it's important to protect your server and the data it holds.

This article will cover the basics of configuring Nginx, a popular open-source web server software, to improve security and protect against common attacks.





###Nginx###

[Nginx](https://nginx.org/en/docs/) is a web server that reverses proxy servers and is known for its high performance and stability. Nginx can be used to protect your web server against common web attacks such as DDoS, SQL injection, and cross-site scripting.

By providing features such as SSL/TLS encryption, access controls and authentication, and hardening the Nginx configuration. Nginx also allows you to monitor and log activity on your web server, which can help you detect and respond to potential security threats.

**Prerequisite:**

Before getting started, you need the following prerequisite.

- Nginx installed.

- Basic knowledge of Nginx.


###Basic configuration options for Nginx###
Once Nginx is installed, you will need to configure it to work with your website. The main configuration file for Nginx is located at  `/etc/nginx/nginx.conf` , or the path to the `nginx.conf` file in Windows. This file contains several options that you can adjust to suit your needs. Some common configuration options include:

**Server blocks:** Nginx uses server blocks to specify which files to serve for different domains or subdomains. A sample server block is given below; this block listens to port 80 and serves content from the root directory `/var/www/html `.

```Nginx 
 server {
    listen 80;
    server_name server.com;
    root /var/www/html;
    index index.html;
}
```
**Location blocks:** Within a server block, you can specify locations that define how Nginx should handle requests for different types of files or URIs. A sample location block is given below; this block handles all the requests with the URI starting with /images and serves the content from the directory `/var/www/images`.

```Nginx
 location /images/ {
    alias /var/www/images/;
}
```

**Basic authentication: **It allows for the setting up of basic authentication for the website, which means that users will need to enter a username and password to access the site. It can be enabled by using the `auth_basic` and `auth_basic_user_file `directives in the server or location block.

```Nginx
location / {
    auth_basic "Restricted Content";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

```

###Securely configuring Nginx###

#####Setting up SSL/TLS encryption#####

One of the most important steps in securing your web server is to enable SSL/TLS encryption. This will ensure that all data transmitted between the web server and the client's browser is encrypted and protected from eavesdropping. In Nginx, you can enable SSL/TLS encryption by obtaining a valid SSL/TLS certificate and configuring Nginx to use it. Here's an example of configuring SSL/TLS in the Nginx server block to listen on port 443 and to use SSL/TLS encryption. The SSL certificate and private key are specified using the `ssl_certificate` and `ssl_certificate_key` directives.

```Nginx
http {
    server {
        listen 443 ssl;
        ssl_certificate /path/to/ssl/certificate.crt;
        ssl_certificate_key /path/to/ssl/private.key;
        ssl_protocols TLSv1.2;
        ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384;
        # Additional server configurations
    }
}
```

#####Configuring access controls and authentication#####

Another important step in securing your web server is configuring access controls and authentication. This will ensure that only authorized users can access the web server and its resources. In Nginx, you can configure access controls and authentication by using the allow and deny directives in the server or location block to specify which IP addresses or networks are allowed to access the web server. Here's an example where the server block is configured to listen on port 80, and only IP addresses in the range 192.168.1.0/24 are allowed to access the web server. All other IP addresses are denied access using the `deny all` directive.

```Nginx
http {
    server {
        listen 80;
        allow 192.168.1.0/24;
        deny all;
        # other server configurations
    }
}
```

#####Hardening the Nginx configuration#####

Hardening the Nginx configuration involves making various changes to the Nginx configuration file to improve security. Here's an example of how to harden the Nginx configuration. The `server_token` directive is set to `off` to prevent Nginx from sending its version number in the HTTP headers. Additionally, the `add_header` directive is used to add security headers to the HTTP response, such as the `X-Frame-Options` header to prevent clickjacking attacks, the `X-XSS-Protection` header to prevent cross-site scripting attacks, and the `X-Content-Type-Options` header to prevent content-type sniffing.


```Nginx
http {
    server_tokens off;
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";
    # other configurations
}
```

###Techniques for monitoring and logging Nginx activity###

Monitoring and logging are important tasks that help you keep track of your web server's activity and detect any suspicious or malicious activity. Nginx provides various logging options, including access and error logs, which can be configured in the Nginx configuration file. Here's an example of configuring access logs in Nginx, where the log format is defined using the `log_format` directive, and the access log is enabled using the `access_log` directive. The logs will be written to the file /var/log/nginx/access.log in this case.


```Nginx
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;
}
```

###Recommendations for keeping your web server secure###

Some recommendations for keeping your webserver secure:

- Use intrusion detection or prevention systems to detect and block malicious activity.

- Use a firewall to restrict incoming and outgoing traffic.

- Regularly back up your website files and databases.

- Regularly audit your web server's security settings and configuration.

- Use a content delivery network (CDN) to distribute the content and reduce the attack surface.

- Regularly scan your web server for vulnerabilities using tools like Nessus or OpenVAS.

###Conclusion###

Securing your web server with Nginx is important in protecting your website and its users. By following best practices and guidelines, you can ensure that your web server is secure and protected from potential threats.

###Reference###

- [The Nginx documentation](https://nginx.org/en/docs/)

- [The OWASP website](https://owasp.org/)