点赞
评论
收藏
分享
举报
ngx_postgres
发表于2020-10-31 14:48

浏览 1.1k

文章标签

授权协议:
BSD 3-Clause "New" or "Revised" license
原作者联系方式:
Copyright (c) 2010, FRiCKLE Piotr Sikora <info@frickle.com> Copyright (c) 2009-2010, Xiaozhe Wang <chaoslawful@gmail.com> Copyright (c) 2009-2010, Yichun Zhang <agentzh@gmail.com> All rights reserved.
功能说明:
与postgre数据库通信模块

Status

This module is production-ready and it's compatible with following nginx releases:

  • 0.7.x (tested with 0.7.60 to 0.7.69),
  • 0.8.x (tested with 0.8.0 to 0.8.55),
  • 0.9.x (tested with 0.9.0 to 0.9.7),
  • 1.0.x (tested with 1.0.0 to 1.0.11),
  • 1.1.x (tested with 1.1.0 to 1.1.12).
  • 1.2.x (tested with 1.2.3 to 1.2.3).
  • 1.3.x (tested with 1.3.4 to 1.3.4).

Configuration directives

postgres_server

  • syntaxpostgres_server ip[:port] dbname=dbname user=user password=pass
  • defaultnone
  • contextupstream

Set details about the database server.

postgres_keepalive

  • syntaxpostgres_keepalive off | max=count [mode=single|multi] [overflow=ignore|reject]
  • defaultmax=10 mode=single overflow=ignore
  • contextupstream

Configure keepalive parameters:

  • max - maximum number of keepalive connections (per worker process),
  • mode - backend matching mode,
  • overflow - either ignore the fact that keepalive connection pool is full and allow request, but close connection afterwards or reject request with 503 Service Unavailable response.

postgres_pass

  • syntaxpostgres_pass upstream
  • defaultnone
  • contextlocationif location

Set name of an upstream block that will be used for the database connections (it can include variables).

postgres_query

  • syntaxpostgres_query [methods] query
  • defaultnone
  • contexthttpserverlocationif location

Set query string (it can include variables). When methods are specified then query is used only for them, otherwise it's used for all methods.

This directive can be used more than once within same context.

postgres_rewrite

  • syntaxpostgres_rewrite [methods] condition [=]status_code
  • defaultnone
  • contexthttpserverlocationif location

Rewrite response status_code when given condition is met (first one wins!):

  • no_changes - no rows were affected by the query,
  • changes - at least one row was affected by the query,
  • no_rows - no rows were returned in the result-set,
  • rows - at least one row was returned in the result-set.

When status_code is prefixed with = sign then original response body is send to the client instead of the default error page for given status_code.

By design both no_changes and changes apply only to INSERTUPDATEDELETEMOVEFETCH and COPY SQL queries.

This directive can be used more than once within same context.

postgres_output

  • syntaxpostgres_output rds|text|value|binary_value|none
  • defaultrds
  • contexthttpserverlocationif location

Set output format:

  • rds - return all values from the result-set in rds format (with appropriate Content-Type),
  • text - return all values from the result-set in text format (with default Content-Type), values are separated by new line,
  • value - return single value from the result-set in text format (with default Content-Type),
  • binary_value - return single value from the result-set in binary format (with default Content-Type),
  • none - don't return anything, this should be used only when extracting values with postgres_set for use with other modules (without Content-Type).

postgres_set

  • syntaxpostgres_set $variable row column [optional|required]
  • defaultnone
  • contexthttpserverlocation

Get single value from the result-set and keep it in $variable.

When requirement level is set to required and value is either out-of-range, NULL or zero-length, then nginx returns 500 Internal Server Error response. Such condition is silently ignored when requirement level is set to optional (default).

Row and column numbers start at 0. Column name can be used instead of column number.

This directive can be used more than once within same context.

postgres_escape

  • syntaxpostgres_escape $escaped [[=]$unescaped]
  • defaultnone
  • contexthttpserverlocation

Escape and quote $unescaped string. Result is stored in $escaped variable which can be safely used in SQL queries.

Because nginx cannot tell the difference between empty and non-existing strings, all empty strings are by default escaped to NULL value. This behavior can be disabled by prefixing $unescaped string with = sign.

postgres_connect_timeout

  • syntaxpostgres_connect_timeout timeout
  • default10s
  • contexthttpserverlocation

Set timeout for connecting to the database.

postgres_result_timeout

  • syntaxpostgres_result_timeout timeout
  • default30s
  • contexthttpserverlocation

Set timeout for receiving result from the database.

Configuration variables

$postgres_columns

Number of columns in received result-set.

$postgres_rows

Number of rows in received result-set.

$postgres_affected

Number of rows affected by INSERTUPDATEDELETEMOVEFETCH or COPY SQL query.

$postgres_query

SQL query, as seen by PostgreSQL database.

Sample configurations

Sample configuration #1

Return content of table cats (in rds format).

http {
    upstream database {
        postgres_server  127.0.0.1 dbname=test
                         user=test password=test;
    }

    server {
        location / {
            postgres_pass   database;
            postgres_query  "SELECT * FROM cats";
        }
    }
}

Sample configuration #2

Return only those rows from table sites that match host filter which is evaluated for each request based on its $http_host variable.

http {
    upstream database {
        postgres_server  127.0.0.1 dbname=test
                         user=test password=test;
    }

    server {
        location / {
            postgres_pass   database;
            postgres_query  SELECT * FROM sites WHERE host='$http_host'";
        }
    }
}

Sample configuration #3

Pass request to the backend selected from the database (traffic router).

http {
    upstream database {
        postgres_server  127.0.0.1 dbname=test
                         user=test password=test;
    }

    server {
        location / {
            eval_subrequest_in_memory  off;

            eval $backend {
                postgres_pass    database;
                postgres_query   "SELECT * FROM backends LIMIT 1";
                postgres_output  value 0 0;
            }

            proxy_pass  $backend;
        }
    }
}

Required modules (other than ngx_postgres):

Sample configuration #4

Restrict access to local files by authenticating against PostgreSQL database.

http {
    upstream database {
        postgres_server  127.0.0.1 dbname=test
                         user=test password=test;
    }

    server {
        location = /auth {
            internal;

            postgres_escape   $user $remote_user;
            postgres_escape   $pass $remote_passwd;

            postgres_pass     database;
            postgres_query    "SELECT login FROM users WHERE login=$user AND pass=$pass";
            postgres_rewrite  no_rows 403;
            postgres_output   none;
        }

        location / {
            auth_request      /auth;
            root              /files;
        }
    }
}

Required modules (other than ngx_postgres):

Sample configuration #5

Simple RESTful webservice returning JSON responses with appropriate HTTP status codes.

http {
    upstream database {
        postgres_server  127.0.0.1 dbname=test
                         user=test password=test;
    }

    server {
        set $random  123;

        location = /numbers/ {
            postgres_pass     database;
            rds_json          on;

            postgres_query    HEAD GET  "SELECT * FROM numbers";

            postgres_query    POST      "INSERT INTO numbers VALUES('$random') RETURNING *";
            postgres_rewrite  POST      changes 201;

            postgres_query    DELETE    "DELETE FROM numbers";
            postgres_rewrite  DELETE    no_changes 204;
            postgres_rewrite  DELETE    changes 204;
        }

        location ~ /numbers/(?<num>\d+) {
            postgres_pass     database;
            rds_json          on;

            postgres_query    HEAD GET  "SELECT * FROM numbers WHERE number='$num'";
            postgres_rewrite  HEAD GET  no_rows 410;

            postgres_query    PUT       "UPDATE numbers SET number='$num' WHERE number='$num' RETURNING *";
            postgres_rewrite  PUT       no_changes 410;

            postgres_query    DELETE    "DELETE FROM numbers WHERE number='$num'";
            postgres_rewrite  DELETE    no_changes 410;
            postgres_rewrite  DELETE    changes 204;
        }
    }
}

Required modules (other than ngx_postgres):

Sample configuration #6

Use GET parameter in SQL query.

location /quotes {
    set_unescape_uri  $txt $arg_txt;
    postgres_escape   $txt;
    postgres_pass     database;
    postgres_query    "SELECT * FROM quotes WHERE quote=$txt";
}

Required modules (other than ngx_postgres):

Testing

ngx_postgres comes with complete test suite based on Test::Nginx.

You can test core functionality by running:

$ TEST_NGINX_IGNORE_MISSING_DIRECTIVES=1 prove

You can also test interoperability with following modules:

by running:

$ prove

License

Copyright (c) 2010, FRiCKLE Piotr Sikora <info@frickle.com>
Copyright (c) 2009-2010, Xiaozhe Wang <chaoslawful@gmail.com>
Copyright (c) 2009-2010, Yichun Zhang <agentzh@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

This software includes also parts of the code from:

  • nginx (copyrighted by Igor Sysoev under BSD license),
  • ngx_http_upstream_keepalive module (copyrighted by Maxim Dounin under BSD license).

See also

已修改于2023-03-09 02:19
创作不易,留下一份鼓励
皮皮鲁

暂无个人介绍

关注



写下您的评论
发表评论
全部评论(0)

按点赞数排序

按时间排序

关于作者
皮皮鲁
这家伙很懒还未留下介绍~
85
文章
2
问答
41
粉丝
相关文章
概述 Nginx 从 1.9.0 开始加入了 stream 模块支持四层的代理,转发和负载均衡。但是,stream 模块的功能相对简单。对需要 ALG 处理的协议比如 FTP 的支持也远远不够。我试着去修改了 Nginx 的源代码,添加了alg模块。使之支持了 FTP主动模式和被动模式下的 ALG 功能。 Github 的源码地址为 : https://github.com/pei-jikui/nginx-alg。代码本身不困难,困难的是如何把代码模块化,有机地融入nginx原有的框架结构中,尽量少地修改已有的框架代码。而后者,需要对stream模块乃至nginx本身的框架和代码有一定的熟悉程度。图 1:FTP被动模式 数据连接 图2 :FTP主动模式 数据连接可能大家会说,Passive 模式不需要ALG 。准确
点赞 6
浏览 3.6k
使用配置方式:install./configure--add-module={module_dir}&&make&&makeinstallconfserver{ listen80; client_max_body_size100m; location/{ roothtml/upload; } #Uploadformshouldbesubmittedtothislocation location/upload{ #Passalteredrequestbodytothislocation upload_pass/example.php; #Storefilestothisdirectory #Thedirectoryishashed,subdirectories0123456789shouldexist
点赞 3
浏览 2.7k
使用方法:1.创建tableCREATETABLE oauth_access_token (id int(10)NOTNULLAUTO_INCREMENT,access_token varchar(255)DEFAULTNULL,expires_in int(10)NOTNULL,last_used_time int(10)NOTNULL,PRIMARYKEY(id),KEY ACCESS_TOKEN (access_token))ENGINE=InnoDBDEFAULTCHARSET=utf8;2.安装Oauth模块cd/work/nginx-1.8.0&&./configure--add-module=/work/nginx-http-oauth-module&&make3.添加配置请参照源码连接中的nginx.conf 4.使用Oauth模块a)创建访问tokenhttp://192.168.1.104/token?appid=
点赞 3
浏览 2k