How to Install ModSecurity 3 + OWASP with Nginx on Rocky Linux 9


ModSecurity, often referred to as Modsec, is a free, open-source web application firewall (WAF). ModSecurity was created as a module for the Apache HTTP Server. However, since its early days, the WAF has grown and now covers an array of HyperText Transfer Protocol request and response filtering capabilities for various platforms such as Microsoft IIS, Nginx, and Apache. ModSecurity’s primary role is to provide protection for web applications by filtering incoming traffic and blocking malicious requests. The WAF can also be configured to monitor traffic for certain types of activity, such as SQL injection attacks, and generate alerts when such activity is detected. In addition to its security benefits, ModSecurity can improve web performance by caching rules and eliminating the need to repeatedly process the same request.

Along with Modsecurity installation, OWASP Core Rule Set (CRS) is commonly used in conjunction which is an open-source set of rules written in ModSecurity’s SecRules language. The CRS is highly regarded in the security industry, and ModSecurity is considered one of the most effective ways to protect web applications from attack. While ModSecurity is not a silver bullet, it is an essential tool in the arsenal of any organization that takes web security seriously.

OWASP Rule Set with ModSecurity can almost instantly help protect your server.

  • Bad user agents
  • DDOS
  • Cross website scripting
  • SQL injection
  • Session hijacking
  • Other Threats

In the following tutorial, you will learn how to install ModSecurity 3 & OWASP Core Rule Set with Nginx on Rocky Linux 9 with example configurations from start to finish.

Update Rocky Linux

First, update your system to ensure all existing packages are up to date.


sudo dnf upgrade --refresh

Install Latest Nginx Stable or Mainline

By default, you can keep your existing version of Nginx installed if you can find a matched version source. If not, installing either the latest stable or mainline build of Nginx is recommended, as the tutorial will go through below.

Remove Existing Nginx Installation

Stop the current Nginx service:

sudo systemctl stop nginx

Now remove the existing Nginx installation as follows:

sudo dnf remove nginx

Now that you have successfully removed the old Nginx version, if you had it installed, to install Nginx mainline, you need to install the dependency for it first, which is dnf-utilities with the following command:

sudo dnf install dnf-utils -y

Next, import the repositories below.

Import Nginx Mainline Repository

sudo tee /etc/yum.repos.d/nginx-mainline.repo<<EOF

name=nginx mainline repo


Users with aarch architecture, replace in the above command baseurl= with baseurl=


Import Nginx Stable Repository

sudo tee /etc/yum.repos.d/nginx-stable.repo<<EOF

name=nginx stable repo


Users with aarch architecture, replace in the above command baseurl= with baseurl=

Install the Nginx

By default, the latest repository for stable Nginx packages is used first. However, the tutorial will install Nginx mainline, so you will need to run the following command to enable the mainline repository as follows:

sudo yum-config-manager --enable nginx-mainline

Note if you prefer stable, do not use the above command and proceed to the next part of the tutorial.

Next, install Nginx mainline as follows:

sudo dnf install nginx
How to Install ModSecurity 3 + OWASP with Nginx on Rocky Linux 9

As above, the tutorial is installing the Nginx latest mainline version straight from Note that you will see a pop-up that notifies you about importing the GPG key during the installation. This is safe to do and is required to finish installing Nginx mainline successfully.

By default, Nginx does not come enabled and is deactivated on installation. To activate your Nginx service, use:


sudo systemctl start nginx

Enable Nginx to be started on boot; use the following command:

sudo systemctl enable nginx

Optionally, verify your version of Nginx. In our case, it is the Nginx Mainline version; use the following command.

nginx -v

Configure FirewallD For Nginx

If you are not replacing an existing Nginx service and installing Nginx for the first time, you may need to configure the firewall for HTTP and HTTPS traffic. An example of how to do this is below:

Allow HTTP traffic use the following command:

sudo firewall-cmd --permanent --zone=public --add-service=http

Allow HTTPS traffic use the following command:

sudo firewall-cmd --permanent --zone=public --add-service=https

Once done, you need to make the changes effective by reloading the firewall:


sudo firewall-cmd --reload

Download Nginx Source

The next step is to Now, and you will need to download the Nginx source code to compile the ModSecurity dynamic module. You must download and store the source package in the directory location /etc/local/src/nginx.

Create and Configure Directories

Create the location as follows:

sudo mkdir /usr/local/src/nginx && cd /usr/local/src/nginx

Download Source Archive

Next, download the Nginx source archive from the downloads page to match the Nginx version you identified earlier. Even if you did not update to the latest version of stable or mainline Nginx and use an older version, you should be able to find a source to match your own.

Nginx downloads page can be found here.

Download the source using the wget command as follows (example only).

sudo wget

Remember it is essential the Nginx version installed matches the downloaded archive, or else you will have failures later on in the tutorial.


Next, extract the archive as follows.

sudo tar -xvzf nginx-1.23.1.tar.gz

Verify Source Version

Next, list the directories files with the ls command as follows.


Example output in your /usr/src/local/nginx directory.

[joshua@rocky-linux-9 nginx]$ ls
nginx-1.23.1  nginx-1.23.1.tar.gz

Next, confirm that the source package is the same as your Nginx version installed on your system, as mentioned earlier.

Install libmodsecurity3 for ModSecurity

The package libmodsecurity3 is the fundamental part of the WAF that does the HTTP filtering for your web applications. You will compile it from the source.

Clone ModSecurity Repository from Github

The first step is the clone from Github, and if you do not have git installed, you will need to execute the following command:


sudo dnf install git -y

Next, clone the libmodsecurity3 GIT repository as follows.

sudo git clone --depth 1 -b v3/master --single-branch /usr/local/src/ModSecurity/

Once cloned, you will need to CD to the directory.

cd /usr/local/src/ModSecurity/

Install libmodsecurity3 Dependencies

Before you compile, you will need to install the following dependencies as follows.

The first task is to install the EPEL repository, and the recommendation is to install both repositories.


First, enable the CRB repository.

sudo dnf config-manager --set-enabled crb

Next, install EPEL using the following (dnf) terminal command.


sudo dnf install \ \

Next, run the following command to install the packages that Modsecurity will require. This should cover most options and features that you can use with Modsecurity and the core rule set.

sudo dnf install doxygen yajl-devel gcc-c++ flex bison yajl curl-devel zlib-devel pcre-devel autoconf automake git curl make libxml2-devel pcre-static pkgconfig libtool httpd-devel redhat-rpm-config wget curl openssl openssl-devel geos geos-devel geocode-glib-devel geolite2-city geolite2-country nano -y

Install GeoIP, you will first need to import the Remi repository.

sudo dnf install dnf-utils -y

Now install GeoIP-devel using the following command.

sudo dnf --enablerepo=remi install GeoIP-devel -y

Now to finish off, install the following GIT submodules as follows.

sudo git submodule init

Then update the submodules:

sudo git submodule update

Building the ModSecurity Environment

The next step is now actually to build the environment first. Use the following command:


sudo ./

Next, run the configure command.

sudo ./configure

Note that you will possibly see the following error.

fatal: No names found, cannot describe anything.

You can safely ignore this and move on to the next step.

Compiling the ModSecurity Source Code

Now that you have built and configured the environment for libmodsecurity3, it is time to compile it with the command make.

sudo make

A handy trick is to specify the -j <number of cpu> as this can significantly increase compiling speed if you have a powerful server.

For example, the server has 6 CPUs, and I can use all 6 or at least 4 to 5 to increase speed.


sudo make -j 6

After compiling the source code, now run the installation command in your terminal:

sudo make install

Note that the installation is done in the /usr/local/modsecurity/, which you will reference later.


Install ModSecurity-nginx Connector

The ModSecurity-nginx connector is the connection point between nginx and libmodsecurity. It is the component that communicates between Nginx and ModSecurity (libmodsecurity3).

Clone ModSecurity-nginx Repository from Github

Similar to the previous step cloning the libmodsecurity3 repository, you will need to clone the connector repository again using the following command:

sudo git clone --depth 1 /usr/local/src/ModSecurity-nginx/

Install ModSecurity-nginx Dependencies

Next, navigate into the Nginx source directory; remember the example below will be different from your version; it is just an example.



cd /usr/local/src/nginx/nginx-1.23.1/

Next, you will compile the ModSecurity-nginx Connector module only with the –with-compat flag as follows:

sudo ./configure --with-compat --add-dynamic-module=/usr/local/src/ModSecurity-nginx

Example output if all has worked correctly so far:

How to Install ModSecurity 3 + OWASP with Nginx on Rocky Linux 9

Now make (create) the dynamic modules with the following command:

sudo make modules

Example output:

How to Install ModSecurity 3 + OWASP with Nginx on Rocky Linux 9

Next, while in the Nginx source directory, use the following command to move the dynamic module you made that was saved at the location objs/ and copy it to the /usr/share/nginx/modules directory.

sudo cp objs/ /usr/share/nginx/modules/

You can store the dynamic module anywhere if you specify the full path when loading.


For users that installed Nginx mainline or stable, the location would be as follows.

sudo cp objs/ /etc/nginx/modules/

Load and Configure ModSecurity-nginx Connector with Nginx

Now that you have compiled the dynamic module and located it accordingly, you need to edit your /etc/nginx/nginx.conf configuration file to get ModSecurity operating with your Nginx webserver.

Enable ModSecurity in nginx.conf

Firstly, you need to specify load_module and path to your modsecurity module.

Open up nginx.conf with any text editor. For the tutorial, nano will be used:

sudo nano /etc/nginx/nginx.conf

Next, add the following line to the file near the top:

load_module modules/;

If you have located the module elsewhere, include the full path.


Now add the following code under the HTTP {} section as follows:

modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/modsec-config.conf;


How to Install ModSecurity 3 + OWASP with Nginx on Rocky Linux 9

If you have located the module elsewhere, include the full path.

Save the file (CTRL+O), then exit (CTRL+X).

Create and Configure Directory and Files for ModSecurity

For the tutorial, you will need to create a directory to store the configuration files and future rules, OWASP CRS.

Use the following command to create the /etc/nginx/modsec directory.


sudo mkdir /etc/nginx/modsec/

You must copy the sample ModSecurity configuration file from our cloned GIT directory.

sudo cp /usr/local/src/ModSecurity/modsecurity.conf-recommended /etc/nginx/modsec/modsecurity.conf

Using your favorite text editor, open the modsecurity.conf file as follows.

sudo nano /etc/nginx/modsec/modsecurity.conf

By default, ModSecurity configuration has the rule engine specified as (DetectionOnly), which in other words, runs ModSecurity and detects all malicious behavior but does not action blocks or ban and logs all the HTTP transactions that it flags. This should only be used if you have lots of false positives or have increased the security level settings to an extreme level and testing to see if any false positives occur.

In the configuration file, change this behavior to (on), found on line 7.

SecRuleEngine DetectionOnly

Change the line to this to enable ModSecurity:

SecRuleEngine On



How to Install ModSecurity 3 + OWASP with Nginx on Rocky Linux 9

Now, you need to locate the following SecAuditLogParts, which is located on line 224.

# Log everything we know about a transaction.
SecAuditLogParts ABIJDEFHZ

This is not correct and needs to be changed. Modify the line to the following:

SecAuditLogParts ABCEFHJKZ

Now save the file using (CTRL+O), then exit (CTRL+X).

The next part is to create the following file modsec-config.conf. Here you will add the modsecurity.conf file along and later on other rules such as OWASP CRS, and if you are using WordPress, the WPRS CRS rule set.


Use the following command to create the file and open it.

sudo nano /etc/nginx/modsec/modsec-config.conf

Once inside the file, add the following line.


include /etc/nginx/modsec/modsecurity.conf

Save the modsec-config.conf file with (CTRL+O), then (CTRL+X) exit.

Lastly, copy ModSecurity’s unicode.mapping file with the CP command as follows.

sudo cp /usr/local/src/ModSecurity/unicode.mapping /etc/nginx/modsec/

Before moving on, you should give your Nginx service a dry run with the following terminal command.

sudo nginx -t

If you have set everything up correctly, you should get the following output:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

To make the changes live, restart your Nginx service using the systemctl command:

sudo systemctl restart nginx

Install OWASP Core Rule Set for ModSecurity

ModSecurity on its own does not protect your web server, and you need to have rules. One of the most famous, respected, and well-known rules is the OWASP CRS rule set. The rules are the most widely used amongst web servers and other WAFs, and most other similar systems base most of their rules on this CRS. Installing this ruleset will automatically give you a great source of protection against most emerging threats on the Internet by detecting malicious actors and blocking them.


Check the OWASP Release tag page to see what is the latest, as the example below may have changed in the future.

First, navigate back to your modsec directory that was created.

cd /etc/nginx/modsec

Using the wget command, download the OWASP CRS 3.3.2 archive, which as of this date the latest stable, but do keep in mind four days ago, the pre-release version dropped, so my advice is to check the link a few lines above to see what the releases are looking like for the core ruleset.


You can download the nightly build for those who want to live on the edge. Only use the nightly if you are prepared to keep re-compiling and checking the CoreRuleSet Github frequently for updates and be more confident at figuring out issues. Technically the nightly can be more secure but potentially can create problems.

For novice users, use the stable version and do not use the below version.


At the time of the creation of the tutorial, the v4.0.0-RC1 pre-release is also available, as mentioned earlier.



Install the Unzip package if you do not have this installed on your server.

sudo dnf install unzip -y

Now unzip the archive, and the tutorial will install the RC candidate as it’s close to the most updated version possible without using the nightly, which can be problematic unless you are experienced with OWASP rules and Modsecurity. Then I recommend using that version for the latest security rules.

sudo unzip v4.0.0-rc1 -d /etc/nginx/modsec

I recommend keeping the versions of the OWASP rule sets since you can download multiple and, in the future, quickly change them in your modsecurity.conf to see which ruleset works the best without issues, such as testing between the releases candidate and nightly or stable and release candidate.

As to before, like the modsecurity.conf sample configuration, OWASP CRS comes with a sample configuration file you need to rename. It is best to use the CP command and keep a backup for the future in case you need to restart again.

sudo cp /etc/nginx/modsec/coreruleset-4.0.0-rc1/crs-setup.conf.example /etc/nginx/modsec/coreruleset-4.0.0-rc1/crs-setup.conf

To enable the rules, open the /etc/nginx/modsec/modsec-config.conf.

sudo nano /etc/nginx/modsec/modsec-config.conf

Once inside the file again, add the following two additional lines:


include /etc/nginx/modsec/coreruleset-4.0.0-rc1/crs-setup.conf
include /etc/nginx/modsec/coreruleset-4.0.0-rc1/rules/*.conf


How to Install ModSecurity 3 + OWASP with Nginx on Rocky Linux 9

Save the file (CTRL+O) and exit (CTRL+T).

Remember, as explained a little earlier, you can technically download multiple versions, modify this file, and do not forget to copy over and whitelist you do, the significant part about the whitelist is that it’s generic for the most part.

As per before, you need to test any new additions to your Nginx service before making it live.

sudo nginx -t

After running the dry-run test, you should get the following output which means everything is correctly working:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Restart your Nginx service to make the changes live as follows:


sudo systemctl restart nginx

Using and Understanding OWASP Core Rule Set

OWASP CRS has many options, the default settings, however, out of the box, will protect most servers immediately without hurting your real visitors and good SEO bots. Below, some areas will be covered to help explain. Further reading would be best to investigate all the options in the configuration files themselves as they have quite a bit of text data to explain.

Open up your CRS-setup.conf file.

sudo nano /etc/nginx/modsec/coreruleset-4.0.0-rc1/crs-setup.conf

Note that this is the dev version configuration with additional items compared to version 3.3.

From here, you can modify most of your OWASP CRS settings.


To break it down, ModSecurity has two modes:

Anomaly Scoring Mode


# -- [[ Anomaly Scoring Mode (default) ]] --
# In CRS3, anomaly mode is the default and recommended mode, since it gives the
# most accurate log information and offers the most flexibility in setting your
# blocking policies. It is also called "collaborative detection mode".
# In this mode, each matching rule increases an 'anomaly score'.
# At the conclusion of the inbound rules, and again at the conclusion of the
# outbound rules, the anomaly score is checked, and the blocking evaluation
# rules apply a disruptive action, by default returning an error 403.

Self-Contained Mode

# -- [[ Self-Contained Mode ]] --
# In this mode, rules apply an action instantly. This was the CRS2 default.
# It can lower resource usage, at the cost of less flexibility in blocking policy
# and less informative audit logs (only the first detected threat is logged).
# Rules inherit the disruptive action that you specify (i.e. deny, drop, etc).
# The first rule that matches will execute this action. In most cases this will
# cause evaluation to stop after the first rule has matched, similar to how many
# IDSs function.

Anomaly Scoring is generally, for most users, the best mode to use.

There are four paranoia levels:

  • Paranoia Level 1 – Default level and recommended for most users.
  • Paranoia Level 2 – Advanced users only.
  • Paranoia Level 3 – Expert users only.
  • Paranoia Level 4 – Not recommended at all, except for exceptional circumstances.
# -- [[ Paranoia Level Initialization ]] ---------------------------------------
# The Paranoia Level (PL) setting allows you to choose the desired level
# of rule checks that will add to your anomaly scores.
# With each paranoia level increase, the CRS enables additional rules
# giving you a higher level of security. However, higher paranoia levels
# also increase the possibility of blocking some legitimate traffic due to
# false alarms (also named false positives or FPs). If you use higher
# paranoia levels, it is likely that you will need to add some exclusion
# rules for certain requests and applications receiving complex input.
# - A paranoia level of 1 is default. In this level, most core rules
#   are enabled. PL1 is advised for beginners, installations
#   covering many different sites and applications, and for setups
#   with standard security requirements.
#   At PL1 you should face FPs rarely. If you encounter FPs, please
#   open an issue on the CRS GitHub site and don't forget to attach your
#   complete Audit Log record for the request with the issue.
# - Paranoia level 2 includes many extra rules, for instance enabling
#   many regexp-based SQL and XSS injection protections, and adding
#   extra keywords checked for code injections. PL2 is advised
#   for moderate to experienced users desiring more complete coverage
#   and for installations with elevated security requirements.
#   PL2 comes with some FPs which you need to handle.
# - Paranoia level 3 enables more rules and keyword lists, and tweaks
#   limits on special characters used. PL3 is aimed at users experienced
#   at the handling of FPs and at installations with a high security
#   requirement.
# - Paranoia level 4 further restricts special characters.
#   The highest level is advised for experienced users protecting
#   installations with very high security requirements. Running PL4 will
#   likely produce a very high number of FPs which have to be
#   treated before the site can go productive.
# All rules will log their PL to the audit log;
# example: [tag "paranoia-level/2"]. This allows you to deduct from the
# audit log how the WAF behavior is affected by paranoia level.
# It is important to also look into the variable
# tx.enforce_bodyproc_urlencoded (Enforce Body Processor URLENCODED)
# defined below. Enabling it closes a possible bypass of CRS.

Test OWASP CRS on your Server

To test if OWASP CRS is working on your server, open up your Internet Browser and use the following:

You should receive a 403 forbidden error. If not, then a step has been missed.



How to Install ModSecurity 3 + OWASP with Nginx on Rocky Linux 9

The most common problem is changing DetectionOnly to On, as covered earlier in the tutorial.

Dealing with False Positives & Custom Rules Exclusion

One of the often never-ending tasks is dealing with false positives, ModSecurity and OWASP CRS do a great job together, but it comes at the cost of your time, but given the protection you get, it is worth it. For starters, never putting the paranoia level up high is the golden rule.


A good rule of thumb is to run the rule set for a few weeks to months with hardly any false positives, then increase, for example, paranoia level 1 to paranoia level 2, so you are not swamped with a ton simultaneously.

Excluding False Positives known Applications

Modsecurity, by default, can whitelist everyday actions that lead to false positives as below:

#SecAction \
# "id:900130,\
#  phase:1,\
#  nolog,\
#  pass,\
#  t:none,\
#  setvar:tx.crs_exclusions_cpanel=1,\
#  setvar:tx.crs_exclusions_dokuwiki=1,\
#  setvar:tx.crs_exclusions_drupal=1,\
#  setvar:tx.crs_exclusions_nextcloud=1,\
#  setvar:tx.crs_exclusions_phpbb=1,\
#  setvar:tx.crs_exclusions_phpmyadmin=1,\
#  setvar:tx.crs_exclusions_wordpress=1,\
#  setvar:tx.crs_exclusions_xenforo=1"

To enable, for example, WordPress, phpBB, and phpMyAdmin as you use all three, uncomment the lines and leave the (1) number intact, change the other services you do not use, for instance, Xenforo to (0) as you do not want to whitelist these rules.

Example below:


SecAction \

You can also modify the syntax, which would be cleaner. For example:

SecAction \

As you can see, removed are the options not needed and added (“) at the end of WordPress for correct syntax.

Excluding Rules Before CRS

To deal with custom exclusions, firstly, you need to change the name from the REQUEST-900-EXCLUSION-RULES-BEFORE-CRS-SAMPLE.conf file with the cp command as follows:

sudo cp /etc/nginx/modsec/coreruleset-3.4-dev/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf.example /etc/nginx/modsec/coreruleset-3.4-dev/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf

Remember when creating exclusion rules, each one must have id:<rule number> and be unique, or else when you test your Nginx service, you will get an error.


Example “id:1544,phase:1,log,allow,ctl:ruleEngine=off”, the id 1544 cannot be used for a second rule.

For example, some REQUEST_URI’s will raise false positives. The example below is two with Google pagespeed beacon and WMUDEV plugin for WordPress:


SecRule REQUEST_URI "@beginsWith /wp-load.php?wpmudev" "id:1544,phase:1,log,allow,ctl:ruleEngine=off"

SecRule REQUEST_URI "@beginsWith /ngx_pagespeed_beacon" "id:1554,phase:1,log,allow,ctl:ruleEngine=off"

As you can see, any URL that begins with the path will be automatically allowed.

Another option is to whitelist IP addresses; a few ways you can go about this:

SecRule REMOTE_ADDR "^195\.151\.128\.96" "id:1004,phase:1,nolog,allow,ctl:ruleEngine=off"
## or ###
SecRule REMOTE_ADDR "@ipMatch,," "phase:1,id:1313413,allow,ctl:ruleEngine=off"

The @ipMatch can be used more extensively for subnets. If you want to deny a subnet or IP address change, allow to deny. With some know-how, you can also create blacklists and whitelists and configure this with fail2ban. The possibilities can often be endless.

One last example is to disable only rules that trigger false positives, not blanket whitelisting the entire path, as you saw with the first REQUEST_URI example. However, this takes more time and testing.

For instance, if you want to remove rules 941000 and 942999 from your /admin/ area as it keeps triggering false bans and blocks for your team, find in your modsecurity logs file the rule ID and then disable only that ID with RemoveByID as the example below:

SecRule REQUEST_FILENAME "@beginsWith /admin" "id:1004,phase:1,pass,nolog,ctl:ruleRemoveById=941000-942999"

Examples can be found on the ModSecurity GIT wiki page.


WordPress WPRS Rule Set for ModSecurity

Another option for WordPress users is to install and run alongside your OWASP CRS rule set, a well-known project entitled WPRS rule set. As this is optional and not for everyone, the tutorial will not cover it in this section.

However, if you want to install this for extra protection using WordPress on your server, please visit our tutorial on Installing WordPress ModSecurity Rule Set (WPRS).

Create ModSecurity LogRotate File

ModSecurity logs can overgrow, so you need to set up log rotating as this is not done for you.

First, create and open your ModSecurity rotate file modsec.

sudo nano /etc/logrotate.d/modsec

Add the following code:

        rotate 31

This will keep logs for 31 days. If you prefer to have less, change 31 to 7 days, equally a week’s worth of logs. You should be rotating daily for ModSecurity. If you need to review the log files having a weekly file will be a disaster to sift through, given how large it will be.


Comments and Conclusion

Overall, deploying ModSecurity to your server will provide instant protection. However, patience, time, and dedication to learning will be such a great feature. The last thing you want is to block SEO bots or, more importantly, real users that could be potential customers.

Remember to test and check logs and not set the security level too high. As great as these software are, they can block legitimate traffic very quickly and, depending if your website is a source of income can have disastrous results.

Share on: