Nginx server security configuration

First, turn off SELinux
Security-Enhanced Linux (SELinux) is a Linux kernel feature that provides security policy protection mechanism supports access control.
However, SELinux brings additional security and the disproportionate use of complexity, cost is not high

sed -i /SELINUX=enforcing/SELINUX=disabled/ /etc/selinux/config

/usr/sbin/sestatus -v # Check status

Second, the least privilege allowed by zoning mount

A separate partition on the server nginx directory.

For example, create a new partition /dev/sda5 (first logical partition), and mounted at /nginx.
Make sure /nginx is noexec,nodev and nosetuid permission to mount

The following is my /etc/fstab mount /nginx information: LABEL=/nginx /nginx ext3 defaults,nosuid,noexec,nodev 1 2

Note: You need to create a new partition using fdisk and mkfs.ext3 command.
Third, to strengthen the Linux security configuration /etc/sysctl.conf

You can control and configure the Linux kernel by editing /etc/sysctl.conf, network settings

# Avoid a smurf attack

net.ipv4.icmp_echo_ignore_broadcasts = 1

# Turn on protection for bad icmp error messages

net.ipv4.icmp_ignore_bogus_error_responses = 1

# Turn on syncookies for SYN flood attack protection

net.ipv4.tcp_syncookies = 1

# Turn on and log spoofed, source routed, and redirect packets

net.ipv4.conf.all.log_martians = 1

net.ipv4.conf.default.log_martians = 1

# No source routed packets here

net.ipv4.conf.all.accept_source_route = 0

net.ipv4.conf.default.accept_source_route = 0

# Turn on reverse path filtering

net.ipv4.conf.all.rp_filter = 1

net.ipv4.conf.default.rp_filter = 1

# Make sure no one can alter the routing tables

net.ipv4.conf.all.accept_redirects = 0

net.ipv4.conf.default.accept_redirects = 0

net.ipv4.conf.all.secure_redirects = 0

net.ipv4.conf.default.secure_redirects = 0

# Don’t act as a router

net.ipv4.ip_forward = 0

net.ipv4.conf.all.send_redirects = 0

net.ipv4.conf.default.send_redirects = 0

# Turn on execshild

kernel.exec-shield = 1

kernel.randomize_va_space = 1

# Tuen IPv6

net.ipv6.conf.default.router_solicitations = 0

net.ipv6.conf.default.accept_ra_rtr_pref = 0

net.ipv6.conf.default.accept_ra_pinfo = 0

net.ipv6.conf.default.accept_ra_defrtr = 0

net.ipv6.conf.default.autoconf = 0

net.ipv6.conf.default.dad_transmits = 0

net.ipv6.conf.default.max_addresses = 1

# Optimization for port usefor LBs

# Increase system file descriptor limit

fs.file-max = 65535

# Allow for more PIDs (to reduce rollover problems); may break some programs 32768

kernel.pid_max = 65536

# Increase system IP port limits

net.ipv4.ip_local_port_range = 2000 65000

# Increase TCP max buffer size setable using setsockopt()

net.ipv4.tcp_rmem = 4096 87380 8388608

net.ipv4.tcp_wmem = 4096 87380 8388608

# Increase Linux auto tuning TCP buffer limits

# min, default, and max number of bytes to use

# set max to at least 4MB, or higher if you use very high BDP paths

# Tcp Windows etc

net.core.rmem_max = 8388608

net.core.wmem_max = 8388608

net.core.netdev_max_backlog = 5000

net.ipv4.tcp_window_scaling = 1

Fourth, remove all unnecessary Nginx module

You need to make the number of modules directly by compiling the source code Nginx minimized. By limiting access to only allow web server module to minimize risk.
You can configure only install nginx modules you need. For example, disabling SSL and autoindex module you can execute the following command:

./configure -without-http_autoindex_module -without-http_ssi_module
make && make install

Change nginx version name, edit the file /h/http/ngx_http_header_filter_module.c?

vim  src/http/ngx_http_header_filter_module.c

static char ngx_http_server_string[] = “Server: nginx” CRLF;

static char ngx_http_server_full_string[] = “Server: ” NGINX_VER CRLF;

//change to

static char ngx_http_server_string[] = “Server: Mohan Web Server” CRLF;

static char ngx_http_server_full_string[] = “Server: Mohan Web Server” CRLF;

Close nginx version number display

server_tokens off

Fifth, based Iptables firewall restrictions

The following firewall script block any addition to allowing:

HTTP (TCP port 80) of a request from
ICMP ping requests from
ntp (port 123) requests output
smtp (TCP port 25) request output

Six control buffer overflow attacks

Edit and set all clients buffer size limit is as follows:

client_body_buffer_size  1K;

client_header_buffer_size 1k;

client_max_body_size 1k;

large_client_header_buffers 2 1k;

client_body_buffer_size 1k (default 8k or 16k) This instruction can specify the buffer size of the connection request entity.
If the value exceeds the specified buffer connection request, then the whole or part of the requesting entity will try to write a temporary file.
client_header_buffer_size 1k  directive specifies the client request buffer size of the head.
In most cases a request header is not greater than 1k, but if there is a large cookie wap from the client that it may be greater than 1k,
Nginx will assign it a larger buffer, this value can be set inside the large_client_header_buffers .
client_max_body_size 1k- directive specifies the maximum allowable size of the client requesting entity connected, it appears in the Content-Length header field of the request.

If the request is greater than the specified value, the client will receive a “Request Entity Too Large” (413) error. Remember, the browser does not know how to display the error.
large_client_header_buffers- specify the client number and size of some of the larger buffer request header use.
Request a field can not be greater than the buffer size, if the client sends a relatively large head, nginx returns “Request URI too large” (414)
Similarly, the head of the longest field of the request can not be greater than one buffer, otherwise the server will return “Bad request” (400). Separate buffer only when demand.
The default buffer size for the operating system paging file size is usually 4k or 8k, if a connection request is ultimately state to keep- alive, it occupied the buffer will be freed.

You also need to improve server performance control timeouts and disconnects the client. Edit as follows:

client_body_timeout 10;
client_header_timeout 10;
keepalive_timeout 5 5;
send_timeout 10;

• client_body_timeout 10; – directive specifies the timeout request entity read. Here timeout refers to a requesting entity did not enter the reading step, if the connection after this time the client does not have any response, Nginx will return a “Request time out” (408) error.
• client_header_timeout 10; – directive specifies the client request header headline read timeout. Here timeout refers to a request header did not enter the reading step, if the connection after this time the client does not have any response, Nginx will return a “Request time out” (408) error.
• keepalive_timeout 5 5; – the first parameter specifies the timeout length of the client and server connections, over this time, the server will close the connection. The second parameter (optional) specifies the response header Keep-Alive: timeout = time value time, this value can make some browsers know when to close the connection to the server not repeat off if you do not specify this parameter , nginx does not send Keep-Alive header information in the response. (This does not refer to how a connection “Keep-Alive”) These two values ??of the parameters can be different.
• send_timeout 10; directive specifies the timeout is sent to the client after the response, Timeout refers not enter a complete state established, completed only two handshakes, more than this time if the client does not have any response, nginx will close the connection.

Seven control concurrent connections

You can use NginxHttpLimitZone module to restrict a specific session or a special case of concurrent connections IP addresses under. Edit nginx.conf:

### Directive describes the zone, in which the session states are stored i.e. store in slimits. ###

### 1m can handle 32000 sessions with 32 bytes/session, set to 5m x 32000 session ###

limit_zone slimits $binary_remote_addr 5m;

### Control maximum number of simultaneous connections for one session i.e. ###

### restricts the amount of connections from a single ip address ###

limit_conn slimits 5

The above represents the remote IP address to limit each client connection can not be open at the same time more than five.

Eight, only allow access to our domain

If the robot is just random scan all domain name servers, that reject the request. You must allow the configuration of the virtual domain or reverse proxy request. You do not use IP addresses to reject.

if ($host !~ ^(||$ ) {
return 444;

Nine, to limit the request method available

GET and POST are the Internet’s most commonly used method. The method of the Web server is defined in RFC 2616. If the Web server is not required to run all available methods, they should be disabled. The following command will filter only allows GET, HEAD and POST methods:

## Only allow these request methods ##

if ($request_method !~ ^(GET|HEAD|POST)$ ) {

return 444;


## Do not accept DELETE, SEARCH and other methods ##

More about HTTP method introduced

• GET method is used to request,

• HEAD method is the same, unless GET request to the server can not return the message body.

• POST method can involve many things, such as storage or update data, or ordering products, or send e-mail by submitting the form. This is usually the use of server-side processing, such as PHP, Perl and Python scripts. If the file you want to upload and server processing the data, you must use this method.

Ten, how to refuse a number of User-Agents?

You can easily stop User-Agents, such as scanners, robotics and abuse your server spammers.

## Block download agents ##

if ($http_user_agent ~* LWP::Simple|BBBike|wget) {

return 403;


Soso and the proper way to prevent robots:

## Block some robots ##

if ($http_user_agent ~* Sosospider|YodaoBot) {

return 403;


XI prevent image hotlinking

Pictures or HTML Daolian mean someone directly with your website address to display pictures on his website. The end result, you need to pay the extra cost of broadband. This is often in the forum and blog. I strongly recommend that you block and prevent hotlinking behavior.

# Stop deep linking or hot linking

location /images/ {

valid_referers none blocked;

if ($invalid_referer) {

return  403;



For example: the redirect and display the specified image

valid_referers blocked;

valid_referers blocked;

if ($invalid_referer) {

rewrite ^/images/uploads.*\.(gif|jpg|jpeg|png)$ last


Twelve, directory restrictions

You can set access permissions on the specified directory. All websites directory should one configuration, allowing only access to the directory.
Access by IP address restrictions
You can restrict access by IP address directory / admin /:

ocation /docs/ {

## block one workstation


## allow anyone in


## drop rest of the world

deny    all;


Via password protected directory, first create the password file and increase the “user” user

mkdir /usr/local/nginx/conf/.htpasswd/

htpasswd -c /usr/local/nginx/conf/.htpasswd/passwd user

Edit nginx.conf, added need protected directories

### Password Protect /personal-images/ and /delta/ directories ###

location ~ /(personal-images/.*|delta/.*) {

auth_basic  “Restricted”;

auth_basic_user_file  /usr/local/nginx/conf/.htpasswd/passwd;


Once the password file has been generated, you can also use the following command to allow access to the user increases

htpasswd -s /usr/local/nginx/conf/.htpasswd/passwd userName

Thirteen, Nginx SSL Configuration

HTTP is a plain text protocol, which is open to passive surveillance. You should use SSL to encrypt your user content.
Create SSL certificate, execute the following command:

cd /usr/local/nginx/conf

openssl genrsa -des3 -out server.key 1024

openssl req -new -key server.key -out server.csr

cp server.key

openssl rsa -in -out server.key

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Edit nginx.conf press following updates:

server {


listen 443;

ssl on;

ssl_certificate /usr/local/nginx/conf/server.crt;

ssl_certificate_key /usr/local/nginx/conf/server.key;

access_log /usr/local/nginx/logs/ssl.access.log;

error_log /usr/local/nginx/logs/ssl.error.log;


Fourteen, Nginx and PHP Security Recommendations

PHP is a popular scripting language on the server side. Edit /etc/php.ini file as follows:

# Disallow dangerous functions

disable_functions = phpinfo, system, mail, exec

## Try to limit resources  ##

# Maximum execution time of each script, in seconds

max_execution_time = 30

# Maximum amount of time each script may spend parsing request data

max_input_time = 60

# Maximum amount of memory a script may consume (8MB)

memory_limit = 8M

# Maximum size of POST data that PHP will accept.

post_max_size = 8M

# Whether to allow HTTP file uploads.

file_uploads = Off

# Maximum allowed size for uploaded files.

upload_max_filesize = 2M

# Do not expose PHP error messages to external users

display_errors = Off

# Turn on safe mode

safe_mode = On

# Only allow access to executables in isolated directory

safe_mode_exec_dir = php-required-executables-path

# Limit external access to PHP environment

safe_mode_allowed_env_vars = PHP_

# Restrict PHP information leakage

expose_php = Off

# Log all errors

log_errors = On

# Do not register globals for input data

register_globals = Off

# Minimize allowable PHP post size

post_max_size = 1K

# Ensure PHP redirects appropriately

cgi.force_redirect = 0

# Disallow uploading unless necessary

# Enable SQL safe mode

sql.safe_mode = On

# Avoid Opening remote files

allow_url_fopen = Off

Fifth, if possible, let Nginx run in a chroot jail

The nginx placed in a chroot jail to reduce the potential for illegal entry into other directories. You can use the traditional and nginx installed with chroot. If possible, that use FreeBSD jails, Xen, OpenVZ virtualization container concept.

XVI firewall level limits the number of connections for each IP

Network server must monitor connections and connection limits per second. PF and Iptales are able to enter your nginx server before the end user to block access.
Linux Iptables: limit the number of connections for each Nginx
following example will prevent from a single IP connection of more than 15 the number of ports 80, 60 seconds.

/sbin/iptables -A INPUT -p tcp –dport 80 -i eth0 -m state –state NEW -m recent –set

/sbin/iptables -A INPUT -p tcp –dport 80 -i eth0 -m state –state NEW -m recent –update –seconds 60  –hitcount 15 -j DROP

service iptables save

According to your specific situation to set the connection limit.

XVII configure the operating system to protect Web servers

Like the above described start SELinux Correct set permissions /nginx document root directory.
Nginx running in user nginx. But the root directory (/ nginx or /usr/local/nginx/html/) should not be set, or the user belongs to the user nginx nginx writable.
Find the error file permissions can use the following command:

find /nginx -user nginx

find /usr/local/nginx/html -user nginx

Make sure you are more ownership of the root or other users, a typical permission settings /usr/local/nginx/html/

ls -l /usr/local/nginx/html/

Sample output:

-rw-r-r- 1 root root 925 Jan 3 00:50 error4xx.html

-rw-r-r- 1 root root 52 Jan 3 10:00 error5xx.html

-rw-r-r- 1 root root 134 Jan 3 00:52 index.html

You must delete the backup files from the vi or another text editor to create:

find /nginx -name ‘.?*’ -not -name .ht* -or -name ‘*~’ -or -name ‘*.bak*’ -or -name ‘*.old*’

find /usr/local/nginx/html/ -name ‘.?*’ -not -name .ht* -or -name ‘*~’ -or -name ‘*.bak*’ -or -name ‘*.old*’

To delete these files by -delete option to find command.

Eighth, the outgoing connections limit Nginx

Hackers can use tools such as wget download your local file server. Iptables from using nginx user to block outgoing connections. ipt_owner module tries to match the creator of locally generated packets. The following example allows only users 80 user connections outside.

/sbin/iptables -A OUTPUT -o eth0 -m owner –uid-owner vivek -p tcp –dport 80 -m state –state NEW,ESTABLISHED  -j ACCEPT

With the above configuration, your nginx server is already very safe and you can publish web pages. However, you should also find more information on security settings according to your site procedures. For example, wordpress or a third-party program.

Leave a comment

Your email address will not be published. Required fields are marked *

Blue Captcha Image


Protected by WP Anti Spam

Hit Counter provided by dental implants orange county