Nginx基础入门教程

本文提供了一份简化的Nginx入门教程,包括Nginx的功能(如负载均衡)、配置结构、常用算法策略(如轮询、加权轮询、ip_hash等)以及location配置的详解。强调通过一手资料与二手书籍结合学习,理解Nginx的配置和使用。
摘要由CSDN通过智能技术生成

本文是综合网上大多数教程而来,取精华去糟粕,本人有强迫症,网上写的太复杂的在我这里都会搞简单!

刚开始或者许久之后回顾的,请看如下入门文章:

https://blog.csdn.net/a419240016/article/details/113533069?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_title~default-8.no_search_link&spm=1001.2101.3001.4242.5&utm_relevant_index=11icon-default.png?t=LBL2https://blog.csdn.net/a419240016/article/details/113533069?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_title~default-8.no_search_link&spm=1001.2101.3001.4242.5&utm_relevant_index=11

图片均为网图,参考链接见文章底部

1.nginx的功能:

1.1 负载均衡

何为负载均衡?后文将详细介绍!

1.1.1 http转发(代理)

1.1.2 http反向转发(反向代理)

正向代理与反向代理2:

2.nginx配置结构

从大到小入手,首先要找到你的nginx安装在哪个位置,后文将详细介绍!

其次,对整体结构要有个初步的了解,就像谈恋爱一样,要一层一层剥开nginx的结构

2.1 文件结构

   2.1.1全局块

   2.1.2events块

   2.1.3http块

      2.1.3.1 server块     

      2.1.3.2 http全局块

main                                # 全局配置

events {                            # nginx工作模式配置
}

http {                                # http设置
    ....

    server {                        # 服务器主机配置
        ....
        location {                    # 路由配置
            ....
        }

        location path {
            ....
        }

        location otherpath {
            ....
        }
    }

    server {
        ....

        location {
            ....
        }
    }

    upstream name {                    # 负载均衡配置
        ....
    }
}

3.算法策略

目前算法就是负载均衡时代理的转发算法

3.1 热备

如果你有2台服务器,当一台服务器发生事故时,才启用第二台服务器给提供服务。服务器处理请求的顺序:AAAAAA突然A挂啦,BBBBBBBBBBBBBB.....

upstream mysvr { 
    server 127.0.0.1:7878; 
    server 192.168.10.121:3333 backup;  #热备     
}

3.2 轮询

nginx默认就是轮询其权重都默认为1,服务器处理请求的顺序:ABABABABAB....

upstream mysvr { 
    server 127.0.0.1:7878;
    server 192.168.10.121:3333;       
}

3.3 加权轮询

跟据配置的权重的大小而分发给不同服务器不同数量的请求。如果不设置,则默认为1。下面服务器的请求顺序为:ABBABBABBABBABB....

upstream mysvr { 
    server 127.0.0.1:7878 weight=1;
    server 192.168.10.121:3333 weight=2;
}

3.4 ip_hash

nginx会让相同的客户端ip请求相同的服务器

upstream mysvr { 
    server 127.0.0.1:7878; 
    server 192.168.10.121:3333;
    ip_hash;
}

3.5 其他

  • down,表示当前的server暂时不参与负载均衡。

  • backup,预留的备份机器。当其他所有的非backup机器出现故障或者忙的时候,才会请求backup机器,因此这台机器的压力最轻。

  • max_fails,允许请求失败的次数,默认为1。当超过最大次数时,返回proxy_next_upstream 模块定义的错误。

  • fail_timeout,在经历了max_fails次失败后,暂停服务的时间。max_fails可以和fail_timeout一起使用。

例子:

upstream mysvr { 
    server 127.0.0.1:7878 weight=2 max_fails=2 fail_timeout=2;
    server 192.168.10.121:3333 weight=1 max_fails=2 fail_timeout=1;    
}

4.上文2中配置细节

4.1 http块-》server块

         4.1.2 location:配置路由以及各种页面的处理情况

现在进入nginx文档直接看一手资料:

对比下看一手英文原始资料和看二手书籍有什么区别

Module ngx_http_core_module

Syntax:location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
Default:
Context:serverlocation

Sets configuration depending on a request URI.

根据请求的URI设置配置

The matching is performed against a normalized URI, after decoding the text encoded in the “%XX” form, resolving references to relative path components “.” and “..”, and possible compression of two or more adjacent slashes into a single slash.

匹配规则是不同于正常的URI,在编码这个有着“%XX”格式的编码之后,解决涉及到相关的路径成员“.”和“..”,并且将两个或者多个斜杠压缩成一个斜杠

A location can either be defined by a prefix string, or by a regular expression. 一个location即不能定义成一个前缀字符串,又不能定义成一个常规表达。

Regular expressions are specified with the preceding “~*” modifier (for case-insensitive matching), or the “~” modifier (for case-sensitive matching). 常规表达是明确“~*”修改和“~” 修改

To find location matching a given request, nginx first checks locations defined using the prefix strings (prefix locations).找到location匹配的请求,nginx首先检查用前缀定义的locations们。

Among them, the location with the longest matching prefix is selected and remembered.其中,最长胡前缀会被选中和记住。

Then regular expressions are checked, in the order of their appearance in the configuration file.规范胡表达是被检查胡,在配置文件的样子的秩序中

The search of regular expressions terminates on the first match, and the corresponding configuration is used.规范表达胡查找取决于第一个匹配,相应的规则也被使用了。

If no match with a regular expression is found then the configuration of the prefix location remembered earlier is used. 如果没有规范表达被发现,那么之前被记住的前缀会被用上。

location blocks can be nested, with some exceptions mentioned below.这个location段是嵌套的,一些成分会在下面提到。

For case-insensitive operating systems such as macOS and Cygwin, matching with prefix strings ignores a case (0.7.7). However, comparison is limited to one-byte locales.

Regular expressions can contain captures (0.7.40) that can later be used in other directives.

If the longest matching prefix location has the “^~” modifier then regular expressions are not checked.  如果最长匹配的前缀location有“^~”修饰语,那么这些规范表达不检查。

Also, using the “=” modifier it is possible to define an exact match of URI and location. If an exact match is found, the search terminates. For example, if a “/” request happens frequently, defining “location = /” will speed up the processing of these requests, as search terminates right after the first comparison. Such a location cannot obviously contain nested locations.

或者,用=修饰符是能定义一个精确的URI和location匹配,如果一个精确的匹配被找到,搜索终止。比如,如果/请求频繁发生,定义的/location会加速这些请求的过程,当第一个比较这个搜索会终止。这样的location明显不能包含嵌套的locations们。

In versions from 0.7.1 to 0.8.41, if a request matched the prefix location without the “ =” and “ ^~” modifiers, the search also terminated and regular expressions were not checked.

Let’s illustrate the above by an example:

location = / {
    [ configuration A ]
}

location / {
    [ configuration B ]
}

location /documents/ {
    [ configuration C ]
}

location ^~ /images/ {
    [ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {
    [ configuration E ]
}

The “/” request will match configuration A, the “/index.html” request will match configuration B, the “/documents/document.html” request will match configuration C, the “/images/1.gif” request will match configuration D, and the “/documents/1.jpg” request will match configuration E.

这个/请求会匹配配置A,这个/index.html请求会匹配配置B,这个/documents/document.html会匹配配置C,这个/images/1.gif会匹配配置D,这个/documents/1.jpg会匹配配置E

The “@” prefix defines a named location. Such a location is not used for a regular request processing, but instead used for request redirection. They cannot be nested, and cannot contain nested locations.

这个@前缀定义了一个准确描述的location.这种location不是用于常规的请求过程,但是用于替代请求重定向。他们不能嵌套,不能包含嵌套的locations.

If a location is defined by a prefix string that ends with the slash character, and requests are processed by one of proxy_passfastcgi_passuwsgi_passscgi_passmemcached_pass, or grpc_pass, then the special processing is performed.

In response to a request with URI equal to this string, but without the trailing slash, a permanent redirect with the code 301 will be returned to the requested URI with the slash appended. If this is not desired, an exact match of the URI and location could be defined like this:

如果一个location被定义为一个前缀字符串以斜杠字符串为结尾,而且请求由这些其中之一处理,proxy_passfastcgi_passuwsgi_passscgi_passmemcached_pass, or grpc_pass,然后这个特殊的处理会被执行。

为了响应URI请求对于这些字符串,但是没有结尾斜杠,一个301永久的重定向会返回给这个URI请求带着这个附加的斜杠。如果这个不是想要的,一个精确匹配的URI和location要定义成下面这个样子

location /user/ {
    proxy_pass http://user.example.com;
}

location = /user {
    proxy_pass http://login.example.com;
}

这段原文介绍是翻译完了,总结一下:

1.首先location用于server和location中

2.语法为

location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }

但是看完了就能搞清楚location是怎么配置的嘛?显然不能!

那怎么办?搞本二手书对比学习一下,看下二手书比这些一手资料有什么不一样的地方。

二手书资料地址:nginx books   可以从前往后一期一期的看,然后对比最原始胡文档看看有没有什么变化和别人的理解和学习思路

到目前为止,学了这么多,学了这么多天,还是不知道怎么用,怎么改,哪怕是最基础的demo都没跑起来,

所以,从现在开始,从功能的角度来分析,一点一点,增量型,敏捷学习!从最基础的功能跑起,一点一点慢慢实现复杂的功能。

首先,就配置个路由

main                                # 全局配置

events {                            # nginx工作模式配置
}

http {                                # http设置

    server {                        # 服务器主机配置
        location {                    # 路由配置
        }
    }

    upstream name {                    # 负载均衡配置
    }
}

修改上面的参数,完成代理到一个接口的任务!

main                                # 全局配置

events {                            # nginx工作模式配置
}

http {                                # http设置

    server {                        # 服务器主机配置
        location {                    # 路由配置
        }
    }

    upstream name {                    # 负载均衡配置
    }
}

现在怎么弄,只有一点理论和上面这个空架子,怎么填?

main、events、up...保持不变,server的location烤屁一下

location  路径{

ip地址

}

拆分问题如下:路径怎么写?ip地址怎么写?

去看看自己上文中跟进原始英文文档总结的,看看能不能自己完成,不借助百度?

看看,搞了这么久还不会,你只是个搬运工和搞翻译的!没有掌握和应用,还是在浪费时间!!!

哀哉!哀哉!古人之错后人哀之而不鉴之,亦复后人哀之矣!

到底是什么问题?如果阅读原始文档,但是无法直接获取或者提取总结较为准确的信息的话,那么阅读官方文档将是失败的,

扩大一步来说,如果没有找到准确概述的中文资料或者网址资料,那么相关次的阅读也是失败的,只会没有效率而浪费时间。

原始文档里提示说location里的configuration 里可以包含:proxy_passfastcgi_passuwsgi_passscgi_passmemcached_pass, or grpc_pass,

于是可以去原始文档中查这些内容,查proxy_pass,在其中比较重要

不看不知道,一看吓一跳,原始文档中的尽然这么多

Syntax:proxy_pass URL;
Default:
Context:locationif in locationlimit_except

proxy  代理

Sets the protocol and address of a proxied server and an optional URI to which a location should be mapped. As a protocol, “http” or “https” can be specified. The address can be specified as a domain name or IP address, and an optional port:

proxy_pass http://localhost:8000/uri/;

or as a UNIX-domain socket path specified after the word “unix” and enclosed in colons:

proxy_pass http://unix:/tmp/backend.socket:/uri/;

If a domain name resolves to several addresses, all of them will be used in a round-robin fashion. In addition, an address can be specified as a server group.

Parameter value can contain variables. In this case, if an address is specified as a domain name, the name is searched among the described server groups, and, if not found, is determined using a resolver.

A request URI is passed to the server as follows:

  • If the proxy_pass directive is specified with a URI, then when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the directive:
    location /name/ {
        proxy_pass http://127.0.0.1/remote/;
    }
    
  • If proxy_pass is specified without a URI, the request URI is passed to the server in the same form as sent by a client when the original request is processed, or the full normalized request URI is passed when processing the changed URI:
    location /some/path/ {
        proxy_pass http://127.0.0.1;
    }
    
    Before version 1.1.12, if  proxy_pass is specified without a URI, the original request URI might be passed instead of the changed URI in some cases.

In some cases, the part of a request URI to be replaced cannot be determined:

  • When location is specified using a regular expression, and also inside named locations.

    In these cases, proxy_pass should be specified without a URI.

  • When the URI is changed inside a proxied location using the rewrite directive, and this same configuration will be used to process a request (break):
    location /name/ {
        rewrite    /name/([^/]+) /users?name=$1 break;
        proxy_pass http://127.0.0.1;
    }
    

    In this case, the URI specified in the directive is ignored and the full changed request URI is passed to the server.

  • When variables are used in proxy_pass:
    location /name/ {
        proxy_pass http://127.0.0.1$request_uri;
    }
    
    In this case, if URI is specified in the directive, it is passed to the server as is, replacing the original request URI.

WebSocket proxying requires special configuration and is supported since version 1.3.13.

阅读完上面proxy_pass的内容,应该就会nginx简单的配置了!

参考:菜鸟教程Nginx 反向代理与负载均衡详解 | 菜鸟教程

           Nginx中文文档:Nginx中文文档

                          Beginner’s Guide

           其他:https://segmentfault.com/a/1190000013600263

                     Nginx基础知识从小白到入门 - 简书    -》  这个链接中推荐了相关课程:

Nginx核心知识150讲_Nginx_Web服务器-极客时间

前端需要的nginx:     前端开发者必备的nginx知识 | ConardLi的blog

这个可以:Nginx配置详解 - 简书

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值