Nginx is a lightweight, high-performance Web server/reverse proxy and email agent (IMAP/POP3) that can run on Unix,gnu/linux,bsd variants, MAC OS x,solaris and Microsoft Windows. According to Netcraft's survey data, 6% of the Internet's domain names use the Nginx Web server. Nginx is one of the servers that solves the c10k problem, unlike traditional servers, Nginx does not rely on thread processing requests, instead it uses a more extensible event-driven (asynchronous) architecture. Nginx has been used on many high-traffic sites, such as Wordpress,hulu,github and SourceForge.
1. Some common sense
- Under Linux, to read a file, you first need to have execute permissions on the folder where the file resides, and then you need to read permissions on the file.
- PHP file execution does not require file execution permissions, only Nginx and PHP-FPM run account Read permissions.
- Upload Trojan, can not list the contents of a folder, with the PHP-FPM running account of the folder Read permissions, the Trojan to execute the command of the rights and PHP-FPM account permissions.
- If the Trojan is to execute the order, need PHP-FPM account to the corresponding SH has the execution authority.
- Read a file within a folder, you do not need to have Read permissions on the folder, only need to execute permissions on the folder.
1, the top of the configuration
User Nginx #定义 Nginx Run and user group
;
#进程文件
pid/var/run/nginx.pid;
#错误日志位置和级别, debug, info, notice, warn, error, crit
error_log/var/log/nginx/error.log warn;
The number of processes #Nginx worker, which can generally be set to the number of available CPU cores.
worker_processes 8;
#每个 worker to open the maximum number of file descriptor limits. The theoretical value should be the maximum number of open files (the system's value ulimit-n) is divided by the number of nginx processes, but the Nginx allocation request is not uniform, so the recommendation is consistent with the Ulimit-n value.
Worker_rlimit_nofile 65535;
2. Events Module
Events {
#设置一个worker进程同时打开的最大连接数
worker_connections 2048;
#告诉nginx收到一个新连接通知后接受尽可能多的连接
multi_accept on;
#设置用于复用客户端线程的轮询方法. If you use Linux 2.6+, you should use Epoll. If you use *BSD, you should use Kqueue. Use
epoll;
}
3, HTTP module
HTTP {#隐藏 Nginx version number to increase security.
Server_tokens off; #开启高效文件传输模式, the sendfile instruction specifies whether Nginx invokes the Sendfile function to output the file, set to on for the normal application, and, if used for downloading applications disk IO heavy load application, to balance disk and network I/O processing speed,
Reduce the load on the system.
Sendfile on;
#是否开启目录列表访问, closed by default.
AutoIndex off;
#告诉 Nginx sends all header files in a packet, not one by one tcp_nopush on; #告诉 Nginx do not cache data, but a paragraph of send-when you need to send data in time, you should set this property to the application, so send a small piece of data information can not immediately get the return value. Nginx will always work in the TCP Nopush state by default. But when opening the front sendfile on; , it is characterized in that the last package of the Nopush is automatically converted to nopush off. To reduce the delay of the 200ms, open nodelay on; Send it out quickly. The conclusion is sendfile on;
Tcp_nopush and Tcp_nodelay are all on when it is turned on.
Tcp_nodelay on; #日志格式设定 Log_format main ' $remote _addr-$remote _user [$time _local] "$request" "$status $body _bytes_sent" $http _refer
Er "' $http _user_agent" "$http _x_forwarded_for" ";
#定义访问日志, set to off to turn off logging and improve performance Access_log/var/log/nginx/access.log main;
#连接超时时间, the unit is seconds Keepalive_timeout 120; #读取HTTP头部的超时时间, the default value is 60. When a client establishes a connection to the server, it begins to receive the HTTP header, and in the process, if no bytes are read to the client at a time interval (timeout), it is considered timed out and returned to the client 408 ("Request timed ouT ") response.
Client_header_timeout 60; #默认值 60.
Similar to Client_header_timeout, this timeout is only valid when the HTTP package is read.
Client_body_timeout 10; #发送响应的超时时间, the default value is 60. That is, the Nginx server sends packets to the client, but the client does not receive the packet.
If a connection exceeds the Send_timeout defined timeout, Nginx will close the connection.
Send_timeout 60; #连接超时后将通过向客户端发送RST包来直接重置连接. When this option is turned on, instead of shutting down the TCP connection with a normal four-shake handshake, Nginx sends the RST reset package directly to the user after a connection times out, releasing all the caches (such as TCP sliding windows) on the Nginx server that are used on the socket without waiting for the user's answer. Rather than a normal shutdown, it causes the server to avoid many TCP connections in Fin_wait_1, fin_wait_2, and time_wait states.
Note that using the RST reset package to close the connection can cause problems that will not be turned on by default.
Reset_timedout_connection off; #要限制连接, you must first have a container for the connection to count, "zone=" is to give it a name, can be casually called, the name should be consistent with the following limit_conn.
$binary _REMOTE_ADDR uses binary to store the address of the client, 1m can store 32,000 concurrent sessions.
Limit_conn_zone $binary _remote_addr zone=addr:5m; #给定的key设置最大连接数.
Here key is addr, we set a value of 100, which means we allow each IP address to open at most simultaneous 100 connections.
Limit_conn addr 100; #对每个连接限速100k.
If an IP allows two concurrent connections, then this IP is the speed limit 200K.
Limit_rate 100k; #include is an instruction that contains the contents of another file in the current file. Here we use it to load the file name extension with the File Type mapping table. Nginx sets the Content-type value of the HTTP request response header based on the mapping relationship.
When the mapping table is not found, use the default value specified by Default-type in nginx.conf.Include/etc/nginx/mime.types;
#设置文件使用的默认的MIME-type Default_type text/html;
#默认编码 CharSet UTF-8; #该模块可以读取预先压缩的gz文件 to reduce CPU resource consumption per request for gzip compression.
When the module is enabled, Nginx first checks for files that have a request for a static file, GZ, and returns the contents of the GZ file directly.
Gzip_static off;
#开启 gzip compression.
gzip on;
# Disables the gzip feature when the client is IE6.
Gzip_disable "Msie6"; #Nginx做为反向代理的时候启用.
Optional value: Off|expired|no-cache|no-sotre|private|no_last_modified|no_etag|auth|any gzip_proxied any; #设置允许压缩的页面最小字节数, the number of page bytes is fetched from the Content-length in the header header.
It is recommended that you set the number of bytes larger than 1k, less than 1k may be more pressing.
Gzip_min_length 1024; #设置数据的压缩等级.
This level can be any number between 1-9, and 9 is the slowest but the maximum compression ratio.
Gzip_comp_level 5; #设置系统获取几个单位的缓存用于存储gzip的压缩结果数据流. For example, 4 4k represents 4k, and applies memory at 4 times times the size of the original data in 4k.
If not set, the default value is to request the same amount of memory space as the original data to store the gzip compression results.
Gzip_buffers 4 16k; #设置需要压缩的数据格式.
Nginx only compresses the text/html by default. Gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml Application/xml+rss
Text/javascript;
#为打开文件指定缓存, the default is not enabled, Max Specifies the number of caches, the recommended and open files are the same, inactive refers to how long after the file has not been requested to delete the cache. Open_File_cache max=65535 inactive=30s;
#多长时间检查一次缓存的有效信息 open_file_cache_valid 30s; #open_file_cache指令中的inactive参数时间内文件的最少使用次数, if this number is exceeded, the file descriptor is always open in the cache.
The last-modified is not changed, because when Nginx is cached on a static file, if it is still being accessed within 30s, its cache persists until you are not visited in 30s.
Open_file_cache_min_uses 2;
#是否记录cache错误 open_file_cache_errors on;
include/etc/nginx/conf.d/*.conf;
include/etc/nginx/sites-enabled/*;
}
4, SERVER module
server {#监听端口, Nginx determines which SERVER segment configuration is used based on the requested HOST. If there is no matching server_name, the first one in the configuration file is used by default.
Plus default_server can be used to specify a default rule when there is no match.
#listen 80;
Listen default_server;
#域名可以有多个, separated server_name www.test.com test.com by Space;
Root/user/share/nginx/html/test;
#404页面配置 Error_page 404/404.html;
#配置 SSL, open when necessary.
SSL on;
SSL_CERTIFICATE/ETC/NGINX/SSL/SERVER.CRT;
Ssl_certificate_key/etc/nginx/ssl/server.key;
Location/{index index.html index.php; #图片缓存时间设置 location ~. *.
(gif|jpg|jpeg|png|bmp|swf) $ {expires 10d; #JS和CSS缓存时间设置 location ~. *.
(JS|CSS)? $ {Expires 1h;
} location ~ [^/]\.php (/|$) {Fastcgi_index index.php;
#开启 path_info Support, the function is to divide the parameters into $fastcgi _script_name and $fastcgi _path_info according to the given regular expression.
#例如: The Fastcgi_script_name is/index.php/id/1,fastcgi_path_info is empty when the request INDEX.PHP/ID/1 not add this row configuration.
#加上之后, Fastcgi_script_name is Index.php,fastcgi_path_info is/ID/1 fastcgi_split_path_info ^ (. +\.php) (. *) $; #此值即是 in PHP The value of $_server[' Script_filename '] fastcgi_param script_filename $document _root$fastcgi_script_name;
Fastcgi_param path_info $fastcgi _path_info;
Fastcgi_param path_translated $document _root$fastcgi_path_info; #指定FastCGI服务器监听端口与地址.
Must be the same as the PHP-FPM setting.
#fastcgi_pass 127.0.0.1:9000;
Fastcgi_pass Unix:/var/run/php5-fpm.sock;
Include Fastcgi_params;
}
}
Second, the common way
- JEANMU can not be executed immediately after: for the upload directory, in the Nginx configuration file to add configuration, so that this directory can not resolve PHP
- Do not see the non-site directory files after the Trojan is executed: Cancel php-fpm Run account Read permissions for other directories
- After the Trojan executes the command cannot execute: Cancels the PHP-FPM account to the SH execution authority
- Permission cannot be too high after command execution: php-fpm account don't use root or join root group
Third, the specific configuration
1, prohibit the PHP file access and implementation
Location ~/(attachments|upload)/.*\. (PHP|PHP5)? $ {
deny all;
}
2, prohibit the IP access
The Forbidden writing
deny 10.0.0.0/24;
The permissible writing
allow 10.0.0.0/24;
Deny all;
3, according to the user's real IP to do connection restrictions
# # Here to obtain the original user's IP address
map $http _x_forwarded_for $clientRealIp {
"" $remote _addr;
~^(? P<firstaddr>[0-9\.] +),?. *$ $firstAddr;
}
# # for the original user IP address restrictions
limit_conn_zone $clientRealIp zone=totalconnlimitzone:20m;
Limit_conn Totalconnlimitzone;
Limit_conn_log_level notice;
# # for the original user IP address restrictions
limit_req_zone $clientRealIp zone=connlimitzone:20m rate=10r/s;
#limit_req zone=connlimitzone burst=10 nodelay;
Limit_req_log_level notice;
# # Specific server configuration servers
{
listen ;
Location ~ \.php$ {
# # up to 5 queues, due to processing 10 requests per second + 5 queues, you send up to 15 requests a second, and then more directly return 503 error to you
limit_req Zone=connlimi Tzone burst=5 Nodelay;
Fastcgi_pass 127.0.0.1:9000;
Fastcgi_index index.php;
Include Fastcgi_params;
}
}
4, after multi-level CDN to obtain the original user's IP address, nginx configuration
Map $http _x_forwarded_for $clientRealIp {
# # No proxy, directly with REMOTE_ADDR
"" $remote _addr;
# # with a regular match, from the x_forwarded_for to obtain the user's original IP
# # such as x-forwarded-for:202.123.123.11, 208.22.22.234, 192.168.2.100,...
# # Here the first 202.123.123.11 is the user's real IP, followed by the other is the CDN server
~^ (? P<firstaddr>[0-9\.] +),?. *$ $firstAddr;
}
# # through the map directive, we created a variable $clientRealIp for Nginx, this is the original user's real IP address,
# # Regardless of whether the user is direct access, or through a series of CDN after the visit, we can get the correct original IP address
5. Hide version Information
Server_tokens off ;
Proxy_hide_header x-powered-by;
or modify the source code when compiling
6. Disabling non-essential methods
if ($request _method!~ ^ (get| head| POST) $ {return 444;
}
7. Disable extension
Location ~*. (Txt|doc|sql|gz|svn|git) $ {
deny all;
}
8, reasonable configuration response head
Add_header strict-transport-security "max-age=31536000";
Add_header x-frame-options deny;
Add_header x-content-type-options Nosniff;
Add_header content-security-policy "default-src ' self"; Script-src ' self ' unsafe-inline ' unsafe-eval ' https://a.disquscdn.com; Img-src ' self ' data:https://www.google-analytics.com; Style-src ' self ' ' unsafe-inline '; Frame-src https://disqus.com ";
Strict-transport-security (referred to as hsts) can tell the browser to always access through HTTPS within the specified max-age
X-frame-options is used to specify whether this page is allowed to be nested by an IFRAME, and deny does not allow any nesting to occur
9. Reject some user-agents
if ($http _user_agent ~* lwp::simple| Bbbike|wget) {return
403;
}
10. Prevent picture hotlinking
valid_referers blocked www.example.com; if ($invalid example.com) {_referer rewrite Images/uploads.*\.
(gif|jpg|jpeg|png) $ http://www.examples.com/banned.jpg Last} 11, control buffer overflow attack client_body_buffer_size 1K;
Client_header_buffer_size 1k;
Client_max_body_size 1k;
Large_client_header_buffers 2 1k;
Client_body_timeout 10;
Client_header_timeout 10;
Keepalive_timeout 5 5;
Send_timeout,
explains the instructions
1, client_body_buffer_size 1k-(default 8k or 16k) to specify the buffer size of the connection request entity. If the connection request exceeds the value specified by the buffer, the whole or part of the request entity will attempt to write to a temporary file. The
2, client_header_buffer_size 1k-directive specifies the buffer size of the client request header. In most cases, a request header will not be greater than 1k, but if there is a larger cookie from the WAP client it may be greater than 1k,nginx will assign it a larger buffer, which can be set in Large_client_header_buffers. The
3, client_max_body_size 1k-directive specifies the maximum request entity size to allow client connections, which appears in the Content-length field of the request header. If the request is greater than the specified value, the client receives a "request Entity Too Large" (413) error. Remember, browsers don't know how to display this error.
4, large_client_header_buffers-specifies the number and size of buffers used by some of the larger request headers of the client. The request field cannot be larger than a buffer size, and if the client sends a larger header, Nginx returns "request URI too Large" (414)
1. The client_body_timeout 10;-instruction specifies the time-out period for the read request entity. Timeout here means that a request entity does not enter the read step, and if the connection exceeds this time and the client does not respond, Nginx returns a "request Time Out" (408) error.
2. The client_header_timeout 10;-directive specifies the time-out period for reading client request header headers. The timeout here means that a request header does not enter the read step, and if the connection exceeds this time and the client does not respond, Nginx returns a "request Time Out" (408) error.
3, keepalive_timeout 5 5; – The first value of the parameter specifies the timeout for the client-server long connection, over which the server closes the connection. The second value of the parameter (optional) specifies the time value of the keep-alive:timeout=time in the answer header, which allows some browsers to know when to close the connection so that the server does not have to repeat the shutdown, if this argument is not specified, Nginx does not send keep-alive information in the answer header. (This does not mean that the two values for a connection "keep-alive" argument can be different.)
4, Send_timeout 10; directive specifies the timeout after sending to the client answer, timeout refers to the failure to enter the full established state, completes only two handshake, if the client does not have any response over this time, Nginx closes the connection.
12, Control concurrent connection
Limit_zone slimits $binary _remote_addr 5m;
Limit_conn Slimits 5;
13, sysctl.conf Configuration
# Avoid a smurf attack net.ipv4.icmp_echo_ignore_broadcasts = 1 # Turn on protection for bad ICMP error messages Net.ip v4.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.defaul T.log_martians = 1 # No source routed packets Here Net.ipv4.conf.all.accept_source_route = 0 Net.ipv4.conf.default.accep
T_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_redi rects = 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 ke Rnel.exec-shield = 1 kerNel.randomize_va_space = 1 # tuen IPv6 net.ipv6.conf.default.router_solicitations = 0 Net.ipv6.conf.default.accept_ra_r
Tr_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 # Opt Imization for Port usefor LBs # Increase System file descriptor limit Fs.file-max = 65535. Allow For more PIDs (to redu CE rollover problems); May-Break Some programs 32768 Kernel.pid_max = 65536 # Increase system IP Port limits Net.ipv4.ip_local_port_range = 200 0 65000 # Increase TCP max buffer size setable using setsockopt () Net.ipv4.tcp_rmem = 4096 87380 8388608 net.ipv4.tcp_wm EM = 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 your use very high BDP paths # TCP Windows etc Net.core.rmem_max = 8388608 NET.CORE.W Mem_max = 8388608 Net.core.Netdev_max_backlog = 5000 net.ipv4.tcp_window_scaling = 1
14. Limit the number of connections per IP at the firewall level
/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---hitcount 15-j DROP
15, limit nginx connection outgoing
/sbin/iptables-a output-o eth0-m owner--uid-owner vivek-p TCP--dport 80-m State--state new,established-j ACCEPT
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.