ModSecurity for Nginx has been available for a while and we can use it freely in our Nginx webserver. ModSecurity was originally deveoped for Apache webserver, but it’s not available to be integrated with Nginx server, even it is in Beta state it works perfectly in our test enviroment. So, let’s see how to install mod_security on Nginx
Let’s start:
Install required dependencies from Github
CentOS/Fedora/RHEL users:
yum install -y gcc make automake autoconf libtool
yum install -y pcre pcre-devel libxml2 libxml2-devel curl curl-devel httpd-devel
Debian/Ubuntu users:
sudo apt-get install libxml2 libxml2-dev libxml2-utils libaprutil1 libaprutil1-dev
Download, compile and install mod_security
git clone https://github.com/SpiderLabs/ModSecurity.git mod_security cd mod_security ./autogen.sh ./configure --enable-standalone-module make
Compile Nginx from source with modsecurity
wget http://www.nginx.org/download/nginx-1.4.2.tar.gz tar -xvpzf nginx-1.4.2.tar.gz cd nginx-1.4.2 ./configure --add-module=../mod_security/nginx/modsecurity make make install
Nginx ModSecurity Configuration
The ModSecurity configuration file must be definded at nginx.conf file, for example:
server { listen 80; server_name localhost; location / { ModSecurityEnabled on; ModSecurityConfig modsecurity.conf; } }
If you need to have custom rules for your mod_security applied to different directories in your website, you can create new mod_security.conf files, for example:
location /secured { ModSecurityConfig modsecurity3.conf; proxy_pass http://secured.mysite.com/; proxy_read_timeout 180s; }
Or you can even turn off mod_security for one directory in particular:
location /unsecured/ { ModSecurityEnabled off; proxy_pass http://unsecured.mysite.com/; proxy_read_timeout 180s; }
Restart Nginx to apply the changes:
service nginx restart
SecDefaultAction "deny,phase:2,status:403"