Installing Nginx with ModSecurity on Ubuntu 24.04
Installing Nginx with ModSecurity on Ubuntu 24.04 involves building Nginx from source with the ModSecurity dynamic module, as official packages for Nginx with ModSecurity integration are not typically available.
ย
1. Install Prerequisites:
ย
Code
ย
sudo apt updatesudo apt install -y build-essential libxml2-dev libpcre3-dev libssl-dev libcurl4-gnutls-dev libyajl-dev doxygen liblmdb-dev git zlib1g-dev pkgconf
2. Download and Compile ModSecurity:
ย
Code
ย
cd /usr/local/srcsudo git clone https://github.com/SpiderLabs/ModSecuritycd ModSecuritysudo git submodule initsudo git submodule updatesudo ./build.shsudo ./configuresudo makesudo make install
3. Download and Compile ModSecurity-nginx Connector:
ย
Code
ย
cd /usr/local/srcsudo git clone https://github.com/SpiderLabs/ModSecurity-nginx.git
4. Download Nginx Source and Build with ModSecurity Module:
ย
First, check your current Nginx version (if installed) usingย
nginx -vย and download the matching source code.ย If you don’t have Nginx, you can choose a stable version from the Nginx website.
ย
Code
ย
# Example for Nginx 1.26.0 (adjust version as needed)cd /usr/local/srcsudo wget https://nginx.org/download/nginx-1.26.0.tar.gzsudo tar -xzvf nginx-1.26.0.tar.gzcd nginx-1.26.0sudo ./configure --with-compat --add-dynamic-module=/usr/local/src/ModSecurity-nginxsudo make modules
5. Copy ModSecurity Module and Configuration:
ย
Code
ย
sudo cp objs/ngx_http_modsecurity_module.so /etc/nginx/modules/sudo cp /usr/local/src/ModSecurity/modsecurity.conf-recommended /etc/nginx/modsecurity.confsudo cp /usr/local/src/ModSecurity/unicode.mapping /etc/nginx/unicode.mapping
6. Configure Nginx to Load ModSecurity:
ย
Editย
/etc/nginx/nginx.confย and add the following lines at the top, outside of anyย httpย block:
ย
Code
ย
load_module modules/ngx_http_modsecurity_module.so;
Then, within yourย
httpย block or a specificย serverย block, enable ModSecurity and include the configuration:
ย
Code
ย
modsecurity on;modsecurity_rules_file /etc/nginx/modsecurity.conf;
7. Test Nginx Configuration and Reload:
ย
Code
ย
sudo nginx -tsudo systemctl reload nginx
8. Install OWASP Core Rule Set (Optional but Recommended):
ย
Code
ย
cd /etc/nginx/sudo git clone https://github.com/coreruleset/coreruleset.gitsudo mv coreruleset/crs-setup.conf.example coreruleset/crs-setup.confsudo mv coreruleset/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf.example coreruleset/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf
Finally, include the CRS rules in yourย
modsecurity.confย or a separate file included by it.




