In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/02 Report--
1. What is Nginx?
Nginx Igor Sysoev from Russia developed Nginx in the C language while working for Rambler Media (http://www.rambler.ru/). As a Web server, Nginx has been providing excellent and stable services for the famous Russian portal Rambler Media.
Igor Sysoev makes Nginx's code open source and gives it the freest 2-clause BSD-like license license. Because Nginx uses event-driven architecture to handle millions of TCP connections concurrently, highly modular design and free licenses make third-party modules that expand Nginx functions emerge in endlessly, and excellent design brings excellent stability, it is widely used as a Web server on high-traffic websites, including Tencent, Sina, NetEase, Taobao and other heavily visited websites.
Nginx is a cross-platform Web server that can run on Linux, FreeBSD, Solaris, AIX, Mac OS, Windows and other operating systems, and it can also use some efficient API unique to the current operating system to improve its performance.
For example, for efficient handling of large-scale concurrent connections, it supports epoll on Linux (epoll is a powerful tool for handling large concurrent network connections on Linux, how epoll works in section 9.6.1), event ports on Solaris, kqueue on FreeBSD, and so on.
For example, for Linux,Nginx to support its unique sendfile system call, this system call can efficiently send the data in the hard disk to the network (there is no need to copy the hard disk data to the user-mode memory and then send it), which greatly reduces the copying action between kernel-state and user-mode data.
two。 Why choose Nginx?
Why choose Nginx? Because it has the following characteristics:
(1) faster
This is shown in two aspects: on the one hand, under normal circumstances, a single request will get a faster response; on the other hand, during peak hours (such as tens of thousands of concurrent requests), Nginx can respond to requests faster than other Web servers.
(2) High scalability
The design of Nginx is very scalable, it is completely composed of many modules with different functions, different levels, different types and very low coupling. Therefore, when you fix Bug or upgrade a module, you can focus on the module itself, regardless of the others. And in the HTTP module, the HTTP filter module is also designed: after a normal HTTP module processes the request, there will be a string of HTTP filter modules to reprocess the results of the request. In this way, when we develop a new HTTP module, we can not only use different levels or different types of modules, such as HTTP core module, events module, log module, but also reuse a large number of existing HTTP filter modules intact. This excellent low-coupling design has created Nginx's huge third-party modules, and of course, open third-party modules are as easy to use as officially released modules.
Nginx modules are embedded in binaries, both officially released modules and third-party modules. This makes third-party modules also have excellent performance and make full use of the high concurrency characteristics of Nginx. Therefore, many high-traffic websites tend to develop customized modules in line with their own business characteristics. Modular design, good expansibility, compiled to Nginx, and started with Nginx startup, but Tengine supports module dynamic loading and unloading mechanism.
(3) High reliability
High reliability is the most basic condition for us to choose Nginx, because the reliability of Nginx is obvious to all, and many high-traffic websites use Nginx on a large scale on core servers. The high reliability of Nginx comes from the excellent design of its core framework code and the simplicity of module design; in addition, the commonly used modules provided by the government are very stable, each worker process is relatively independent, and the master process can quickly "pull" new worker sub-processes to provide services when a worker process goes wrong.
(4) low memory consumption
In general, 10,000 inactive HTTP Keep-Alive connections consume only 2.5MB memory in Nginx, which is the basis for Nginx to support highly concurrent connections.
(5) more than 100000 concurrent connections are supported on a single machine.
This is a very important feature! With the rapid development of the Internet and the double growth of the number of Internet users, major companies and websites need to deal with a large number of concurrent requests. A Server that can withstand more than 100000 concurrent requests during the peak period will undoubtedly be favored by everyone. In theory, the upper limit of concurrent connections supported by Nginx depends on memory, and 100000 is far from capped. Of course, the ability to handle more concurrent requests in a timely manner is closely related to business characteristics, and chapters 8-11 of this book will explain in detail how to achieve this feature.
(6) Hot deployment
The separate design of master management process and worker worker process enables Nginx to provide hot deployment function, that is, it can upgrade the executable file of Nginx under the premise of 7 × 24-hour service. Of course, it also supports updating configuration items, changing log files, and so on without stopping the service.
(7) the freest BSD license agreement
This is a powerful driving force for the rapid development of Nginx. The BSD license agreement not only allows users to use Nginx for free, it also allows users to directly use or modify Nginx source code in their own projects, and then release it. This attracts countless developers to continue to contribute their wisdom to Nginx.
(8) support event-driven, AIO, mmap
Basic functions of 3.Nginx:
(1) web server for static resources, which can cache open file descriptors.
(2) reverse proxy server of http, smtp, pop3 protocols (protects the server, filters bad user requests for the server, encapsulates user requests, acts as some service areas, and provides caching to reduce back-end pressure)
(3) cache acceleration and load balancing
(4) support FastCGI (fpm,LNMP), uWSGI (Python)
(5) Modular (non-DSO mechanism) filter, zip, ssi and image resizing
(6) support SSL,https service.
4. Extended function
Virtual machines based on name and IP
Support for Keepalive
Support for smooth upgrad
Customized access logs and support for log storage performance using log buffers
Support for url rewrite
Support path aliases
Support access control based on IP and users
Support rate limit, support concurrency limit
The basic architecture of 5.Nginx:
A master process. Responsible for generating multiple worker processes.
Event driven: epoll (Linux) kqueue (BSD)
ICompo Multiplexer: select,poll,rt signal
Support for sendfile and sendfile64
Support for AIO
Support for mmap memory mapping
The working mode of nginx: non-blocking, event-driven, multiple master processes are generated by one worker process, and each worker responds to n requests.
6. Module type:
Core module, Standard HTTP modules, Optional HTTP modules, Mail modules, third-party module
7. Source code installation
Yum-y install gcc gcc-c++yum-y install pcre pcre-develyum-y install zlib zlib-develyum-y install openssl openssl-develtar xf nginx-VERSION.tarcd nginx-VERSIONgroupadd-r nginxuseradd-r nginx- g nginx./configure-- help (get help)-- with-xx: originally did not start, start up -- without-xx: originally started Stop starting. / configure-- prefix=/usr/local/nginx-- conf-path=/usr/local/nginx/conf/nginx/nginx.conf-- user=nginx-- group=nginx-- error-log-path=/var/log/nginx/error.log-- http-log-path=/var/log/nginx/access.log-- pid-path=/var/run/nginx/nginx.pid-- lock-path=/var/log/nginx.lock-- with-http_ssl_module-- with-http_stub_ Status_module-- with-http_gzip_static_module-- with-http_flv_module-- with-http_mp4_module-- http-client-body-temp-path=/var/tmp/nginx/client-- http-proxy-temp-path=/var/tmp/nginx/proxy-- http-fastcgi-temp-path=/var/tmp/nginx/fastcgi-- http-uwsgi-temp-path=/var/tmp/nginx/uwsgimake-j 4 & & make installmkdir-pv / var/tmp/nginx/ {client Proxy,fastcgi,uwsgi} start nginx/usr/local/nginx/sbin/nginx
8. Profile introduction
Main configuration segment: global configuration segment
Event {}: define the working characteristics of the event model
Http {}: define configurations related to the http protocol
Configuration instruction: to end with a semicolon.
Support the use of variables:
Built-in variables: the module provides built-in variable definitions
Custom variable: set var_name value
Instructions for the main configuration segment:
Configuration necessary for normal operation
1.user username [groupname]; specify the users and groups running the worker process
2.pid / path/to/pid_file; specifies the pid file of the nginx daemon
Pid / var/run/nginx/nginx.pid
3.worker_rlimit_nofile number; specifies the maximum number of file handles that can be opened by all worker processes
Optimize the configuration of performance
1.worker_processes #; number of worker processes; usually slightly less than the number of CPU physical cores; auto is supported
2.worker_cpu--affinity cpumask... (example: 00000001 00000010 00000100)
Pros: improve cache hit ratio
Cpumask:
0000 0001 cpu no. 1
0000 0010 cpu no. 2
3.timer_resolution: timer resolution. Lowering this value can reduce the number of gettimeofday () system calls.
4.worker_priotity number; indicates the nice value of the worker process (the smaller the value, the higher the priority)
Event-related configuration
1.accept_mutex {off | on}
Master dispatches load balancing locks that users use when requesting to each worker process; on means that multiple worker can take turns, serialize regions to respond to new requests.
2.lock_file file
Lock file path used by accept-mutex
3.use [epoll | rtsing | select | poll]
Indicates the event mode used. It is recommended to let Nginx choose on its own.
4.worker_connections number
Sets the maximum number of concurrent connections that a single worker process can handle; (but sockets are limited)
Worker_connections * work_processes
< 60000 用于调试、定位问题(编译时加入--with-debug) 1.daemon {on|off}; 是否以守护进程方式运行nginx;调试时应该设置为Off 2.master_process {on|off}; 是否以master/worker模型来运行nginx,调试时可设置为Off 3.error_log 位置级别{debug,info,notice,warn,error,crit,altert,emerg} 总结: 常需要进行调整的参数:worker_processes,worker_connections,worker_cpu_affinity,worker_priority nginx -s {stop,quit,reopen,reload} nginx -t :测试语法 9.Nginx作为web服务器时使用的配置: http{}:由ngx_http_core_module模块所引入; 配置框架: http{ upstream{...} server { location {...} 类似于httpd中的,用于定义URL与本地文件系统的映射关系,可有多个 }#每个server类似于httpd中的一个 } 配置指令 1.server{}:定义一个虚拟主机 server{ listen 8080; server_name www.bearlu.com; root "/vhost/web1"; } 2.listen:指定监听的地址和端口 listen address[:port] listen port; 3.server_name Name...:名称还可以使用正则表达式(~开头)通配符 (1)先做精确匹配检查; (2)左侧通配符匹配检查:*.magedu.com (3)右侧通配符匹配检查:mail.* (4)正则表达式匹配检查:~*.*\magedu\.com$ (5)default_server 4.root path;设置资源路径映射;用于指明请求的URL所对应的资源所在的文件系统上的起始路径 5.location [= | ~ | ~* | ^~ | url] {...} location @name {...} 允许根据用户请求的URL来匹配定义的各location;匹配到时,此请求将被相应的location配置块中的配置所处理,例如访问控制。 =:精确匹配检查 ~:正则表达式模式匹配检查,区分字符大小写 ~*:正则表达式模式匹配检查,不区分字符大小写 ^~:URI的前半部分匹配,不支持正则表达式 记住:匹配的优先级:=、^~、~、~*、不带符号的location(越后,优先级越低) 6.alias path; 用于location配置段,定义路径别名; 注意:root表示指明路径为对应的location "/" URL alias表示路径映射,即location指令后定义的URL是相对与alias所指明的路径而言; 7.index file; 默认主页面 8.error_page code [...] 状态码 [=code] URL|@name 根据http响应状态码来指明特用的错误页面; error_page 404 /404_customed.html error_page 404 =200 /404_customed.html [=code]:以指定的响应码进行响应,而不是默认的原来的响应,默认表示以新资源的状态码为其响应码 9.基于IP的访问控制 allow、deny IP/network allow IP、网络 10.基于用户的访问控制 basic、digest auth_basic "验证原因" auth_basic_user_file /etc/nginx/users/.htpasswd; 用htpasswd -c (第一次创建) -m(使用MD5码) /etc/nginx/users/.htpasswd tom 创建用户账号和密码文件 11.SSL listen 443 ssl server_name www.magedu.com ssl_certificate /etc/nginx/ssl/nginx.crt;(证书) ssl_certificate_key /etc/nginx/ssl/nginx.key;(私钥) 12.stub_status {on | off};nginx状态统计页面 仅能用户location上下文。并且allow IP; deny all; 显示结果: Active connections:6 ----->The number of all connections currently open
Number of connections accepted by server
Number of connections processed by accepts
Request processed by handled, in keep-alive mode
Requests
The number of connections that Reading is receiving the request status
The number of connections that the Writing request has been received and is processing the request or sending the response
The number of connections that Waiting is in keep Keepalive connection mode and is active.
13.rewrite URL rewriting
Format: rewrite regex replacement flag
Rewrite ^ / images/ (. *\ .jpg) $/ imgs/$1 break
IP/images/a/b/c/1.jpg-> IP/imgs/a/b/c/1.jpg
Function: domain name switching and redirection
Flag: last: after this rewrite rule is rewritten, it is no longer processed by other rewrite rules. Instead, the URL initiates the request again after the rewrite by User Agent, and executes the similar process from scratch.
Break: once this rewrite rule is rewritten, the request is initiated and will no longer be detected by any rewrite rules in the current location
Redirect: temporary redirect to return a new URL with a 302 response code. (domain name can be changed)
Permanent: the URL returned with a 301 response code for permanent redirection.
14.if context
Syntax: if (condition) {...}
Application scenarios: server, location
Condition:
(1) variable name: if the variable value is an empty string or starts with "0", it is false.
(2) comparison expression composed of variables as operands (=,! =)
(3) pattern matching operation of regular expression
~: case-sensitive pattern matching
~ *: case-insensitive pattern matching
! ~ and! ~ *: reverse the above two tests
(4) whether the test path is a file:-f,!-f
(5) Test whether the specified path is a directory:-d,!-d
(6) the existence of test files:-e,!-e
(7) Test whether the file has execution permissions:-x,!-x
For example:
If ($http_user_agent ~ * MSIE) {rewrite ^ (. *) $/ msie/$1 break;}
15. Hotlink protection
Location ~ *\. (jpg | gif | jpeg | png) ${valid_referer none blocked www.magedu.com; if ($invalid_referer) {rewrite ^ / http://www.magedu.com/403.html}}
16. Customize the access log format
Log_format main "$remote_addr $remote_user [$time_local] $request" access_log logs/access.log main
You can use the built-in variables of each module of nginx here
17. Configuration related to network connection
1. Keepalive_timeout #; timeout for persistent connections
2.keepalive_requests #; the maximum number of resources that can be requested on a persistent connection
3.keepalive_disable [msie6 | safari | none]; disables persistent connections for the specified type of UserAgent
| 4.tcp_nodelay on | whether off; uses the TCP_NODELAY option for persistent connections. Turn it on if you want to optimize the user experience. Otherwise, wait for sufficient quantity before returning. |
5.client_header_timeout #; the timeout for reading the header of the http request message
6.client_body_timeout #; the timeout for reading the body portion of the http request message
7.send_timeout #; the timeout for sending the corresponding message
Summary
The above is the brief introduction of Nginx introduced by the editor to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to the website!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.