Build an efficient and secure Nginx Web server

Source: Internet
Author: User
Tags web hosting nginx server nginx reverse proxy

One by one. Why choose Nginx to build a Web server Apache and Nginx are the two most popular web servers currently used, Apache appeared earlier than Nginx. Apache http server (Apache) is the world's top-ranked Web server software, transliteration, Apache, is an open source web server of the Software Foundation, can run almost all computer platforms, Next Open API interface, any organization and individual can extend and add a variety of functions on it, to achieve their own customized features. Nginx ("Engine x") is a high-performance HTTP and reverse proxy server and also a  IMAP/POP3/SMTP proxy server. nginx  was developed by  Igor Sysoev  for the second  Rambler.ru  site of Russian traffic, and the first public version of 0.1.0 was released on October 4, 2004. It publishes the source code in the form of a BSD license, which is known for its stability, rich feature set, sample configuration files, and consumption of low system resources. In the early days of the internet, the size of the site is not very large, the traffic is very light, a site to visit a maximum of tens of thousands of IPs a day, this time Apache can fully meet the needs, people are more for it to develop a variety of modules, such as rewrite modules, access control lists, cache modules and so on. But with the rapid development of the Internet, the website I visit to increase exponentially, large-scale web site in addition to increasing hardware input, the typical Web server Apache this time is also inadequate, but Apache is not perfect, and no longer suitable for large-scale systems. Why? Because his process pattern is simple and flexible, it is not suitable for large-scale applications, especially when it takes a lot of memory application code like PHP to handle. So Nginx began to rise, the original design is the Russian engineers for large sites to solve high concurrency design. So the doomed high concurrency is its eternal advantage. Again is the reverse proxy, now a large web site division of detail, which server processing data flow, which processing static files, these who command, usually with Nginx reverse proxy to the intranet server, so that the role of load balanced shunt. Again Nginx highly modular design, the writing module is relatively simple. nginx  is a high-performance  Web  and reverse proxy server with many very advantageous features: as a  Web  server: Use fewer resources than  apache,nginx Support for more concurrent connections and higher efficiency, which makes  Nginx is especially popular with web hosting providers. Capable of supporting up to  50,000 concurrent connections, thanks to   for choosing epoll and kqueue  as a development model. As a Load Balancer server:  nginx can support both  Rails  and  php internally, as well as  http Proxy Server   external services. Nginx writing,  in C is much better than perlbal , whether it is system resource overhead or  CPU  usage efficiency. Nginx installation is very simple, the configuration file is very concise (also can support Perl syntax), Bugs very few servers:  nginx Start is particularly easy, and can be almost uninterrupted operation, even if the run for several months do not need to restart. You will also be able to upgrade your software version in the event of uninterrupted service. Two Nginx installation 1, Installation instructions system environment:  centos-6.6 Software:  nginx-1.8.0.tar.gz installation method:  Source compilation installation Location:  /opt/program/ NGINX-1.8.0: HTTP://NGINX.ORG/EN/DOWNLOAD.HTML2, installation must be software # yum install gcc-c++# yum  -y install zlib zlib-devel openssl openssl–devel pcre pcre-devel#  find -name nginx#./nginx#./nginx/sbin/nginx#./nginx-1.2.6/objs/nginx Check the system installed Nginx: Uninstall the original nginx#  YUM REMOVE NGINX3, install, and compile upload the installation package files to/opt/software by doing the following: # cd /opt/program# mkdir  NGINX# TAR -ZXVF&NBSP, .... /software/nginx-1.8.0.tar.gz# cd nginx-1.8.0# ./configure –prefix=/opt/program/nginx Note: This is the specified Nginx installation directory, most users are accustomed to installing under/usr/local/nginx #  make  compiling the # make install  installation 4, configuring the service entry to modify the firewall configuration: # vi + /etc/sysconfig/ Iptables Adding configuration Items-a input -m state –state new -m tcp -p tcp – Dport 80 -j accept Restart firewall # service iptables restart5, boot method 1# /opt/program/ Nginx/sbin/nginx -c /opt/program/nginx/sbin/nginx/conf/nginx.conf Method 2# /opt/program/nginx/sbin/ Nginx Query Nginx main process number # ps -ef | grep nginx force stop # pkill -9 nginx Restart # /opt /program/nginx/sbin/nginx -s reload Test in # netstat –na|grep 80# browser HTTP://IP : 803 configuration Nginx Support High Concurrency 1, nginx general optimization editing nginx.conf, modify the relevant parameters to optimize. worker_processes 8; The number of nginx  processes is recommended according to the number of CPUs, generally it is a multiple of   (for example, 2 four-core CPU is counted as 8). worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000  01000000 10000000;worker_rlimit_nofile 65535; This directive refers to the maximum number of file descriptors opened by a nginx  process, and the theoretical value should be the maximum number of open files (ulimit -n) and nginx  The number of processes is divided, but the nginx  allocation request is not uniform, so it is best to keep the value of ulimit -n  consistent. Now open the number of files in the linux 2.6 kernel for 65535,worker_rlimit_nofile should be filled in 65535 accordingly. worker_connections 65535; the maximum number of connections allowed per process,  theoretically each nginx  server is worker_processes*worker_connections. keepalive_timeout 60;keepalive  time-out period. client_header_buffer_size 4k; client request the buffer size of the head, this can be set according to your system paging size, generally a request header size will not exceed 1k, but because the general system paging is greater than 1k, So this is set to paging size. open_file_cache max=65535 inactive=60s; This will specify the cache for the open file, the default is not enabled,max  specify the number of caches, the recommended number of open files consistent, inactive   is how long it takes to delete a cache after a file has not been requested. open_file_cache_valid 80s; this refers to how long it takes to check the cache for valid information. The minimum number of times the file is used in the inactive parameter time in the open_file_cache_min_uses 1;open_file_cache  directive, and if this number is exceeded, the file descriptor is always opened in the cache, as in the previous example, If a file is not used once within inactive  time, it will be removed. 2, optimization of kernel parameters sysctl.conf optimized Linux kernel. The number of net.ipv4.tcp_max_tw_buckets = 6000timewait , by default, is 180000. NET.IPV4.IP_LOCAL_PORT_RANGE = 1024 65000 allows the system to playThe port range to open. Net.ipv4.tcp_tw_recycle = 1 Enable timewait  Quick Recycle. Net.ipv4.tcp_tw_reuse = 1 turn on reuse. Allows time-wait sockets  to be re-used for new tcp  connections. Net.ipv4.tcp_syncookies = 1 turns on Syn cookies, cookies  is enabled when a syn  wait queue overflow occurs. The backlog  of the listen  function in the net.core.somaxconn = 262144web  application defaults to the net.core.somaxconn of our kernel parameters.   is limited to 128, and the ngx_listen_backlog  defined by nginx  defaults to 511, so it is necessary to adjust this value. NET.CORE.NETDEV_MAX_BACKLOG = 262144 the maximum number of packets that are allowed to be sent to the queue when each network interface receives a packet at a rate that is faster than the rate at which the kernel processes these packets. The maximum number of tcp  sockets in the net.ipv4.tcp_max_orphans = 262144 system are not associated with any one of the user file handles. If this number is exceeded, the orphan connection is immediately reset and a warning message is printed. This limitation is only to prevent a simple dos  attack, not to rely too much on it or artificially reduce the value, but should increase this value (if the memory is increased). NET.IPV4.TCP_MAX_SYN_BACKLOG = 262144 records the maximum number of connection requests that have not yet received the client acknowledgment information. For systems with 128m  memory, the default value is 1024, and the small memory system is 128. The net.ipv4.tcp_timestamps = 0 time stamp avoids winding the serial number. A 1gbps  link will definitely encounter a previously used serial number. Timestamps allow the kernel to accept this "exception" packet. You need to turn it off here. Net.ipv4.tcp_synack_retries = 1 in order to open the connection to the end, the kernel needs to send a syn  with a response to the previous Syn  the ACK. The second handshake in the so-called three-time handshake. This setting determines the number of syn+ack  packets sent before the kernel abandons the connection. Net.ipv4.tcp_syn_retries = 1 the number of syn  packets sent before the kernel abandons the connection. Net.ipv4.tcp_fin_timeout = 1 If the socket is closed by this side, this parameter determines how long it remains in the fin-wait-2  state. The peer can make an error and never shut down the connection, or even accidentally become a machine. The default value is 60  seconds. The usual value of the 2.2  kernel is 180  seconds, 3 You can press this setting, but remember that even if your machine is a light load web  server, there is a risk of memory overflow due to a lot of dead sockets, Fin- wait-2   is less dangerous than fin-wait-1  because it can only eat 1.5k  memory, but they have a longer lifetime. Net.ipv4.tcp_keepalive_time = 30 the frequency of sending keepalive  messages when keepalive ,tcp . The default is 2 hours. After the above optimization, Nginx can support more than 50,000 of concurrent volume. Four Nginx Security Configuration network There are too many methods of nginx security configuration, this article according to their own actual environment, choose the appropriate nginx security Configuration policy. 1, delete all unnecessary nginx module directly by compiling Nginx source code to minimize the number of modules. Minimize risk by restricting only the Web server access module. For example, to disable SSL and AutoIndex modules you can execute the following command: #./configure –without-http_autoindex_module –without-http_ssi_module#  make# make install the following command to see which module can open an account or close:#./configure –help |  when compiling the Nginx server Less then disable the Nginx module that you cannot use. 2, install the SELinux policy to harden Nginx web server default SELinux does not protect the Nginx web server, I install and compile protection software here. Install the required environment support to compile SELinux #&nbspYum -y install selinux-policy-targeted selinux-policy-devel download SELinux policy to enhance nginx  Web server. # cd /opt# wget  ' http://downloads.sourceforge.net/project/selinuxnginx/se-ngix_1_0_10. TAR.GZ?USE_MIRROR=NCHC ' Unzip the file # tar -zxvf se-ngix_1_0_10.tar.gz compile the file # cd se-ngix_1_0_10/ Nginx# make will output the following:compiling targeted nginx module/usr/bin/checkmodule: loading  Policy configuration from tmp/nginx.tmp/usr/bin/checkmodule: policy configuration  loaded/usr/bin/checkmodule: writing binary representation  (version 6)  to  tmp/nginx.modcreating targeted nginx.pp policy package# rm tmp/ Nginx.mod.fc tmp/nginx.mod Install the generated nginx.pp selinux module: # /usr/sbin/semodule -i nginx.pp3, Control buffer overflow Attack edit nginx.conf to set the buffer size limit for all clients. # vi /usr/local/nginx/conf/nginx.conf Edit and set the size limit for all client buffers as follows: ## start: size limits & buffer overflows # #client_body_buffer_size  1K;client_header_buffer_size  1k;client_max_body_size 1k;large_client_header_buffers 2 1k;## end: size limits  & buffer overflows # #4, control concurrent connections use the Nginxhttplimitzone module to restrict concurrent connections to a specified session or to an IP address under special circumstances. Edit nginx.conf:limit_zone slimits  $binary _remote_addr 5m;limit_conn slimits 5; The above indicates that the client that restricts each remote IP address can open a connection no more than 5 simultaneously. 5. Limit the available request methods get and post are the most common methods on the Internet. The  web server method is defined in rfc 2616. If the Web server does not require all available methods to be enabled, they should be disabled. The following instruction will filter only allow 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 # #6, Rejecting some user-agents you can easily block user-agents, such as scanners, bots, and spammers who misuse your servers. ## block download agents # #if   ($http _user_agent ~* lwp::simple| Bbbike|wget) &nbsp {return 403;} # #阻止Soso和有道的机器人: ## block some robots # #if   ($http _user_agent ~* sosospider| Yodaobot)  {return 403;} 7, prevent the picture hotlinking picture or HTML hotlinking means that someone directly uses the image address of your website to display on his website. As a result, you will need to pay extra broadband fees. Need to block and prevent hotlinking behavior. # stop deep linking or hot linkinglocation /images/ {valid_referers  none blocked www.example.com example.com;if  ($invalid _referer)  {return 403 ;}} 8. Limit the number of connections per IP at the firewall level the network server must monitor connections and connection limits per second. Both PF and iptales can block end-user access before entering your Nginx server. Linux iptables: Limit the number of nginx connections The following example blocks the number of connections from more than 15 connections to port 80 from an IP within 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 dropseRvice iptables save I set only 10 Nginx links allowed in the same ip 60 second. 9: Configure the operating system to protect the Web server Nginx program is generally run with user nginx. However, the root directory (/nginx or/usr /local/nginx/html) should not be set to user nginx or user nginx writable. Locate the file with the wrong permissions using the following command: # find /nginx -user nginx# find /usr/local/nginx/html - User nginx Make sure you have more ownership of root or other users, a typical permission setting/usr/local/nginx/html/ls -l /usr/local/nginx/html/ Example 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 Delete a backup file created by vi or another text editor: # 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* ' &NBsp;-or -name  ' *.old* ' removes these files by using the-delete option of the Find command. 10. Restrict Nginx connection outgoing hackers will use tools such as wget to download local files for your server. Use Iptables to block outgoing connections from Nginx users. The Ipt_owner module attempts to match the creator of the locally generated packet. In the example below, only user users are allowed to use the 80 connection outside. This article just according to their own needs to build a suitable Web server, I hope to help you. Nginx is a good tool to improve the pieces, Nginx function is not limited to building a Web server, its more features have yet to continue to develop, I look forward to the nginx can bring us more surprises.


This article from "rendering unchanged Yesterday" blog, declined reprint!

Build an efficient and secure Nginx Web server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.