nginx配置笔记

栏目: 服务器 · Nginx · 发布时间: 5年前

内容简介:nginx配置不常写,看了又忘,真是尴尬。那就再看一次,然后把不会的记录一下,下次 就只要看这篇笔记,就能快速想起来了。.. code:: bash

nginx变量

nginx配置不常写,看了又忘,真是尴尬。那就再看一次,然后把不会的记录一下,下次 就只要看这篇笔记,就能快速想起来了。

nginx 的变量名前面有一个 $ ,与bash一致,例如:

.. code:: bash

set $a "hello";
set $b "$a, $a";

那么 $a 是 "hello",而 $b 是 "hello, hello"

nginx变量的作用范围是整个全局的。但是每个请求都有自己的变量副本:

.. code:: nginx

    server {
        listen 8080;

        location /foo {
            echo "foo = [$foo]";
        }

        location /bar {
            set $foo 32;
            echo "foo = [$foo]";
        }
    }

.. code:: bash

$ http localhost:8080/foo
foo = []

$ http localhost:8080/bar
foo = [32]

请求bar虽然会给 foo 赋值,但并不影响另外一次请求里的 foo

set_unescape_uri 指令能够将uri中类似 %20 解码出来,例如:

.. code:: nginx

location /echo {
    set_unescape_uri $name $arg_name;
    echo "uri = $uri";
    echo "request_uri = $request_uri";
    echo "name = $name";
}

.. code:: bash

$ http 'localhost:8080/echo?name=hi lo'
uri = /echo
request_uri = /echo?name=hi%20lo
name = hi lo

其中 arg_xxx 就会对应uri中的某个key,所以会有无穷无尽个这种参数啦。

nginx中map的意思是映射,举个例子:

.. code:: nginx

map $args $foo {
    default     0;
    debug       1;
}

$args 匹配 debug 时, $foo 被设置成 1,否则为 0。

.. code:: nginx

    map $args $foo {
        default 0;
        debug 1;
    }

    server {
        listen 8080;
        location / {
            default_type text/html;
            content_by_lua '
                ngx.say("<p>hello, world</p>")
                ';
        }

        location /map {
            echo "foo = $foo";
        }
    }

.. code:: bash

$ curl 'localhost:8080/map'
foo = 0
$ curl 'localhost:8080/map?debug'
foo = 1

nginx中的子请求,实际上只调用了一些函数,而并没有另外新建socket连接等,例如:

.. code:: nginx

location /main {
    echo_location /foo;
    echo_location /bar;
}

location /foo {
    echo foo;
}

location /bar {
    echo bar;
}

.. code:: bash

$ curl 'http://localhost:8080/main'
foo
bar

nginx变量在父请求和子请求之间是不相互影响的。但是有些nginx模块不遵循此规则。

nginx配置

想要知道某条指令的将会在nginx的11个请求处理阶段的哪个阶段进行, 需要自行 翻阅对照文档和源码。

nginx 常用配置文件

  • 静态文件web服务器

.. code:: nginx

location /static/ {
    default_type text/html;
    root /var/;
    autoindex on;
}

.. [#] https://openresty.org/download/agentzh-nginx-tutorials-zhcn.html

.. [#] http://www.nginxguts.com/2011/01/phases/


以上所述就是小编给大家介绍的《nginx配置笔记》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

精益创业方法论

精益创业方法论

龚焱 / 机械工业出版社 / 2015-3 / 69.00元

为什么无数新创企业以失败告终? 为什么天才点子、完美计划和完美的执行是导致失败的关键? 颠覆性、创造性、混乱状况是否可以加以管理? Facebook在6年间以病毒一样惊人的速度传播,微信短短两年获得了6亿用户,这些公司都遵循着一套科学、严密的创业流程和工业方法,这种方法教你认清自以为是的假象,让你在亚马逊丛林的迷雾探险时成功找到水源,一切不是未来时,而是现在时,再砰然心动的点子、......一起来看看 《精益创业方法论》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

随机密码生成器
随机密码生成器

多种字符组合密码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具