Nginx는 원래 C10k의 문제를 해결하기 위해 웹 서버로 만들어졌습니다. 웹 서버로서 엄청난 속도로 데이터를 제공할 수 있습니다. 그러나 Nginx는 단순한 웹 서버 그 이상입니다. 이를 역방향 프록시로 사용하여 Unicorn 또는 Puma와 같은 느린 업스트림 서버와 쉽게 통합할 수도 있습니다. 트래픽을 적절하게 분산하고(로드 밸런서), 미디어를 스트리밍하고, 이미지 크기를 동적으로 조정하고, 콘텐츠를 캐시하는 등의 작업을 수행할 수 있습니다. 기본 nginx 아키텍처는 마스터 프로세스와 해당 작업자 프로세스로 구성됩니다. 마스터는 구성 파일을 읽고 작업자 프로세스를 유지 관리하며 작업자는 실제로 요청을 처리합니다.
nginx를 시작하려면 다음을 입력하세요.
[sudo] nginx
nginx 인스턴스가 실행 중일 때 해당 신호를 보내 관리할 수 있습니다:
[sudo] nginx -s signal
사용 가능한 신호:
stop – 메이
/etc/nginx/nginx.conf
,/usr/local/etc/nginx/nginx .conf
또는 /usr/local/nginx/conf/nginx.conf
구성 파일은 다음 부분으로 구성됩니다.
/etc/nginx/nginx.conf
,
/usr/local/etc/nginx/nginx.conf
,或
/usr/local/nginx/conf/nginx.conf
配置文件的由下面的部分构成:
指令 – 可选项,包含名称和参数,以分号结尾
gzip on;
上下文 – 分块,你可以声明指令 – 类似于编程语言中的作用域
worker_processes 2; # 全局上下文指令http { # http 上下文 gzip on; # http 上下文中的指令 server { # server 上下文 listen 80; # server 上下文中的指令 } }
指令类型
当使用相同的指令在不同的继承模型中进行操作时,必须小心谨慎。有三种类型的指令,每种都有自己的继承模型。
普通指令
在每个上下文仅有唯一值。而且,它只能在当前上下文中定义一次。在子级上下文中覆盖父级的值只在当前子级上下文中有效。
gzip on; gzip off; # 非法,不能在同一个上下文中指定同一普通指令2次server { location /downloads { gzip off; } location /assets { # gzip is on here } }
数组指令
在同一上下文中添加多条指令,将添加多个值,而不是完全覆盖。在子级上下文中定义指令将覆盖给父级上下文中的值。
error_log /var/log/nginx/error.log; error_log /var/log/nginx/error_notive.log notice; error_log /var/log/nginx/error_debug.log debug; server { location /downloads { # 下面的配置会覆盖父级上下文中的指令 error_log /var/log/nginx/error_downloads.log; } }
行动指令
行动是改变事情的指令。根据模块的需要,它继承的行为可能会有所不同。例如 rewrite 指令,只要是匹配的都会执行:
server { rewrite ^ /foobar; location /foobar { rewrite ^ /foo; rewrite ^ /bar; } }
如果用户想尝试获取 /sample:
server的rewrite将会执行,从 /sample rewrite 到 /foobar
location /foobar 会被匹配
location的第一个rewrite执行,从/foobar rewrite到/foo
location的第二个rewrite执行,从/foo rewrite到/bar
return 指令提供的是不同的行为:
server { location / { return 200; return 404; } }
在上述的情况下,立即返回200。
处理请求
在 Nginx 内部,你可以指定多个虚拟服务器,每个虚拟服务器用 server{} 上下文描述。
server { listen *:80 default_server; server_name netguru.co; return 200 "Hello from netguru.co"; } server { listen *:80; server_name foo.co; return 200 "Hello from foo.co"; } server { listen *:81; server_name bar.co; return 200 "Hello from bar.co"; }
这将告诉 Nginx 如何处理到来的请求。在检查给定的 IP 端口组合时,Nginx 会先测试哪个虚拟主机有设置 listen 指令。
然后,server_name 指令的值将检测 Host 头(存储着主机域名)。
Nginx 将会按照下列顺序选择虚拟主机:
匹配sever_name指令的IP-端口主机
拥有default_server标记的IP-端口主机
首先定义的IP-端口主机
如果没有匹配,拒绝连接。
例如下面的例子:
Request to foo.co:80 => "Hello from foo.co"Request to www.foo.co:80 => "Hello from netguru.co"Request to bar.co:80 => "Hello from netguru.co"Request to bar.co:81 => "Hello from bar.co"Request to foo.co:81 => "Hello from bar.co"
server_name
指令
server_name指令接受多个值。它还处理通配符匹配和正则表达式。
server_name netguru.co www.netguru.co; # exact matchserver_name *.netguru.co; # wildcard matchingserver_name netguru.*; # wildcard matchingserver_name ~^[0-9]*\.netguru\.co$; # regexp matching
当有歧义时,nginx 将使用下面的命令:
确切的名字
最长的通配符名称以星号开始,例如“* .example.org”。
最长的通配符名称以星号结尾,例如“mail.**”
首先匹配正则表达式(按照配置文件中的顺序)
Nginx将存储三个哈希表,用于存储具体名称、以星号开头的通配符和以星号结尾的通配符。如果结果不在任何表中,则将按顺序进行正则表达式测试。
值得谨记的是
server_name .netguru.co;
是一个来自下面的缩写
server_name netguru.co www.netguru.co *.netguru.co;
有一点不同,.netguru.co
存储在第二张表,这意味着它比显式声明的慢一点。
listen
listen 127.0.0.1:80;
listen 127.0.0.1; # by default port :80 is usedlisten *:81;
listen 81; # by default all ips are usedlisten [::]:80; # IPv6 addresseslisten [::1]; # IPv6 addresses
listen unix:/var/run/nginx.sock;🎜🎜 명령어 유형 🎜🎜 🎜 다른 상속 모델에서 작동하는 동일한 지시문입니다. 세 가지 유형의 지시문이 있으며 각각 고유한 상속 모델이 있습니다. 🎜🎜🎜Normal directives🎜🎜🎜에는 컨텍스트별로 고유한 값만 있습니다. 또한 현재 컨텍스트에서는 한 번만 정의할 수 있습니다. 하위 컨텍스트에서 상위 값을 재정의하는 것은 현재 하위 컨텍스트에서만 유효합니다. 🎜
listen localhost:80; listen netguru.co:80;🎜🎜Array Directives🎜🎜🎜 동일한 컨텍스트에 여러 지시문을 추가하면 전체 적용 범위 대신 여러 값이 추가됩니다. 하위 컨텍스트에서 지시어를 정의하면 상위 컨텍스트의 값이 재정의됩니다. 🎜
# /etc/nginx/nginx.confevents {} # events context needs to be defined to consider config validhttp { server { listen 80; server_name netguru.co www.netguru.co *.netguru.co; return 200 "Hello"; } }🎜🎜Action Instructions🎜🎜🎜Action은 사물을 바꾸라는 지시입니다. 모듈의 필요에 따라 상속되는 동작이 달라질 수 있습니다. 예를 들어, rewrite 명령은 다음과 일치하는 한 실행됩니다: 🎜
server { listen 80; server_name netguru.co; root /var/www/netguru.co; }🎜사용자가 /sample을 얻으려고 시도하는 경우: 🎜🎜🎜🎜서버의 rewrite가 실행되고 /sample에서 /foobar🎜🎜🎜로 다시 작성됩니다. 🎜location /foobar가 일치합니다. 🎜🎜🎜🎜location의 첫 번째 다시 쓰기 실행, /foobar에서 /foo🎜🎜🎜🎜location으로의 rewrite의 두 번째 다시 쓰기 실행, 그리고 /foo에서 /bar🎜🎜🎜🎜rewrite의 두 번째 다시 쓰기 실행 지침은 다른 동작을 제공합니다. 🎜
netguru.co:80/index.html # returns /var/www/netguru.co/index.htmlnetguru.co:80/foo/index.html # returns /var/www/netguru.co/foo/index.html🎜위의 경우 200이 즉시 반환됩니다. 🎜🎜🎜요청 처리🎜🎜🎜Nginx 내에서는 여러 가상 서버를 지정할 수 있으며, 각 가상 서버는 서버 컨텍스트로 설명됩니다.{} 🎜
location /foo/ { # ...}🎜이것은 Nginx에게 들어오는 요청을 처리하는 방법을 알려줍니다. 주어진 IP 포트 조합을 확인할 때 Nginx는 먼저 청취 지시문 세트가 있는 가상 호스트를 테스트합니다. 🎜🎜그런 다음 server_name 지시문의 값은 Host 헤더(호스트 도메인 이름을 저장함)를 감지합니다. 🎜🎜Nginx는 다음 순서로 가상 호스트를 선택합니다: 🎜
/foo /fooo /foo123 /foo/bar/index.html ...🎜🎜
server_name
지시문 🎜🎜🎜server_name 지시문은 여러 값을 허용합니다. 또한 와일드카드 일치 및 정규식도 처리합니다. 🎜server { listen 80; server_name netguru.co; root /var/www/netguru.co; location / { return 200 "root"; } location /foo/ { return 200 "foo"; } } netguru.co:80 / # => "root"netguru.co:80 /foo # => "foo"netguru.co:80 /foo123 # => "foo"netguru.co:80 /bar # => "root"🎜모호한 경우 nginx는 다음 명령을 사용합니다: 🎜
= - Exact match ^~ - Preferential match ~ && ~* - Regex match no modifier - Prefix match🎜는 🎜
location /match { return 200 'Prefix match: matches everything that starting with /match'; } location ~* /match[0-9] { return 200 'Case insensitive regex match'; } location ~ /MATCH[0-9] { return 200 'Case sensitive regex match'; } location ^~ /match0 { return 200 'Preferential match'; } location = /match { return 200 'Exact match'; } /match/ # => 'Exact match'/match0 # => 'Preferential match'/match2 # => 'Case insensitive regex match'/MATCH1 # => 'Case sensitive regex match'/match-abc # => 'Prefix match: matches everything that starting with /match'🎜의 약어이며 약간 다르다는 점을 기억할 가치가 있습니다.
.netguru.co
는 두 번째 테이블에 저장되므로 명시적으로 Slow로 선언된 테이블보다 작습니다. . 🎜🎜🎜듣기
명령🎜🎜在很多情况下,能够找到 listen 指令,接受IP:端口值
listen 127.0.0.1:80; listen 127.0.0.1; # by default port :80 is usedlisten *:81; listen 81; # by default all ips are usedlisten [::]:80; # IPv6 addresseslisten [::1]; # IPv6 addresses
然而,还可以指定 UNIX-domain 套接字。
listen unix:/var/run/nginx.sock;
你甚至可以使用主机名
listen localhost:80; listen netguru.co:80;
但请慎用,由于主机可能无法启动 nginx,导致无法绑定在特定的 TCP Socket。
最后,如果指令不存在,则使用 *:80
。
有了这些知识 – 我们应该能够创建并理解运行 nginx 所需的最低配置。
# /etc/nginx/nginx.confevents {} # events context needs to be defined to consider config validhttp { server { listen 80; server_name netguru.co www.netguru.co *.netguru.co; return 200 "Hello"; } }
root, location, 和 try_files 指令
root 指令
root 指令设置请求的根目录,允许 nginx 将传入请求映射到文件系统。
server { listen 80; server_name netguru.co; root /var/www/netguru.co; }
根据给定的请求,指定 nginx 服务器允许的内容
netguru.co:80/index.html # returns /var/www/netguru.co/index.htmlnetguru.co:80/foo/index.html # returns /var/www/netguru.co/foo/index.html
location
指令
location指令根据请求的 URI 来设置配置。location [modifier] path
location /foo/ { # ...}
如果没有指定修饰符,则路径被视为前缀,其后可以跟随任何东西。
以上例子将匹配
/foo /fooo /foo123 /foo/bar/index.html ...
此外,在给定的上下文中可以使用多个 location 指令。
server { listen 80; server_name netguru.co; root /var/www/netguru.co; location / { return 200 "root"; } location /foo/ { return 200 "foo"; } } netguru.co:80 / # => "root"netguru.co:80 /foo # => "foo"netguru.co:80 /foo123 # => "foo"netguru.co:80 /bar # => "root"
Nginx还有一些修饰符可以用于连接location。因为每个修饰符都有自己的优先级,所以它们会影响 location 模块在使用时的行为。
= - Exact match ^~ - Preferential match ~ && ~* - Regex match no modifier - Prefix match
Nginx 会先检查精确匹配。如果找不到,我们会找优先级最高的。如果之前的匹配尝试失败,正则表达式会按照出现的顺序逐个进行测试。至少,最后一个前缀匹配将被使用。
location /match { return 200 'Prefix match: matches everything that starting with /match'; } location ~* /match[0-9] { return 200 'Case insensitive regex match'; } location ~ /MATCH[0-9] { return 200 'Case sensitive regex match'; } location ^~ /match0 { return 200 'Preferential match'; } location = /match { return 200 'Exact match'; } /match/ # => 'Exact match'/match0 # => 'Preferential match'/match2 # => 'Case insensitive regex match'/MATCH1 # => 'Case sensitive regex match'/match-abc # => 'Prefix match: matches everything that starting with /match'
try_files
指令
尝试不同的路径,找到一个路径就返回。
try_files $uri index.html =404;
所以对于 /foo.html
请求,它将尝试按以下顺序返回文件:
$uri ( /foo.html )
index.html
如果什么都没找到则返回 404
有趣的是,如果我们在服务器上下文中定义 try_files,然后定义匹配的所有请求的 location —— try_files 将不会执行。
这是因为在服务器上下文中定义的 try_files 是它的 pseudo-location,这是最不可能的位置。因此,location/的定义将比pseudo-location更为明确。
server { try_files $uri /index.html =404; location / { } }
因此,你应该避免在 server 上下文中出现 try_files:
server { location / { try_files $uri /index.html =404; } }
위 내용은 Nginx의 기본 개념은 무엇입니까의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!