下面是一个完整的 http 块的配置示例:
http {
# 设置worker进程数
worker_processes auto;
# 设置每个worker进程最大连接数
worker_connections 512;
# 设置长连接超时时间
keepalive_timeout 65;
# 设置server_name的hash桶大小
server_names_hash_bucket_size 128;
# 设置客户端请求头缓冲区大小
client_header_buffer_size 2k;
}
用于配置具体的虚拟主机,包括监听的端口、域名、SSL证书、反向代理等。主要的server配置项包括:
下面是一个简单的server块的配置示例:
server {
# 监听的端口和IP地址
listen 80;
# 指定虚拟主机的域名
server_name example.com www.example.com;
# 网站的根目录
root /var/www/example.com;
# 默认的首页文件
index index.html;
# 访问日志的保存路径和格式
access_log /var/log/nginx/example.access.log combined;
# 错误日志的保存路径和格式
error_log /var/log/nginx/example.error.log;
location /images/ {
root /data/www;
}
location /images/ {
alias /data/www/images/;
}
location / {
if ($request_method=POST) {
return 405;
}
}
location / {
limit_except GET POST {
deny all;
}
}
location / {
proxy_pass http://backend;
}
location / {
root /data/www;
}
location / {
try_files $uri $uri/ /index.html;
}
location / {
rewrite ^/admin/(.*)$ /$1 break;
}
Nginx 的内部结构是由核心部分和一系列的功能模块所组成。这样划分是为了使得每个模块的功能相对简单,便于开发,同时也便于对系统进行功能扩展。Nginx 将各功能模块组织成一条链,当有请求到达的时候,请求依次经过这条链上的部分或者全部模块,进行处理。例如前面讲到的 http 请求,会有11个处理阶段,而每个阶段有对应着许多在此阶段生效的模块对该 http 请求进行处理。同时,Nginx 开放了第三方模块编写功能,用户可以自定义模块,控制 http 请求的处理与响应,这种高度可定制化催生了 Nginx 的大量第三方模块,也使得 Nginx 定制化开发在各大互联网公司十分流行。
关于 Nginx 模块的分类有很多种方式,目前网上博客中写的较多的是按照功能进行分类,有如下几大类:
对于官方提供的模块,我们可以直接在官网文档上学习,学习的方式和学习其他互联网组件的方式一致,首先学习如何使用,在用至熟练后可以深入分析其源码了解功能实现背后的原理。
我们以前面介绍到的 Nginx 的限速模块(limit_req模块)进行说明。首先是掌握该模块的用法,在该模块的官方地址中,有关于该模块的详细介绍,包括该模块提供的所有指令以及所有变量说明。此外,还有比较丰富的指令用例。在多次使用该指令并自认为掌握了该模块的用法之后,想了解限速背后的原理以及相关算法时,就可以深入到源码学习了。
进入 Nginx 的源码目录,使用ls查看源码文件,限速模块是在 http 目录中的。
[root@server nginx-1.17.6]# cd src/
[root@server src]# ls
core event http mail misc os stream
[root@server src]# ls http/modules/ngx_http_limit_*.c
http/modules/ngx_http_limit_conn_module.c
http/modules/ngx_http_limit_req_module.c
代码块12345678
找到 Nginx 模块对应的代码文件后,我们就可以阅读里面的代码进行学习。往往源码的阅读是枯燥无味的,我们可以借助海量的网络资源辅助我们学习。这里就有一篇文章,作者深入分析了 Nginx 的限流模块的源码以及相应限流算法,最后进行了相关的实验测试。通过这样一个个模块深入学习,最后在使用每一个 Nginx 指令时,也会非常熟练,最后成为 Nginx 高手。
这里我们演示在 Nginx 中使用第三方模块。 Openresty 社区提供了一款 Nginx 中的 Echo 模块,即echo-nginx-module。在 Nginx 中添加了该模块后,我们在配置文件中可以使用该模块提供的 echo 指令返回用户响应,简单方便。该模块的源码在 github 上,并且有良好的文档和使用示例,非常方便开发者使用。
现在我们在 Nginx 的源码编译阶段加入该第三方模块,具体操作如下:
[root@server shencong]# pwd
/root/shencong
[root@server shencong]# mkdir nginx-echo
# 下载 nginx 源码包和第三方模块的源码包
[root@server shencong]# wget http://nginx.org/download/nginx-1.17.6.tar.gz
[root@server shencong]# wget https://github.com/openresty/echo-nginx-module/archive/v0.62rc1.tar.gz
# 解压
[root@server shencong]# tar -xzf nginx-1.17.6.tar.gz
[root@server shencong]# tar -xzf v0.62rc1.tar.gz
[root@server shencong]# ls
echo-nginx-module-0.62rc1 nginx-1.17.6 nginx-1.17.6.tar.gz nginx-echo v0.62rc1.tar.gz
[root@server shencong]# cd nginx-1.17.6
# 使用--add-module添加第三方模块,参数为第三方模块源码
[root@server shencong]# ./configure --prefix=/root/shencong/nginx-echo --add-module=/root/shencong/echo-nginx-module-0.62rc1
编译完成后,我们就可以去nginx-echo目录中的 nginx.conf文件中添加echo 指令 。准备如下的配置(可以参参考社区提供的示例):
...
http {
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
# 新增测试 echo 指令配置
location /timed_hello {
default_type text/plain;
echo_reset_timer;
echo hello world;
echo "'hello world' takes about $echo_timer_elapsed sec.";
echo hiya igor;
echo "'hiya igor' takes about $echo_timer_elapsed sec.";
}
location /echo_with_sleep {
default_type text/plain;
echo hello world;
echo_flush; # ensure the client can see previous output immediately
echo_sleep 2.5; # in sec
echo "'hello' takes about $echo_timer_elapsed sec.";
}
}
}
...
启动 Nginx 后,我们就可以在浏览器上请求者两个 URI 地址,看到相应 echo 返回的信息了。第二个配置是使用了 echo_sleep 指令,会使得请求在休眠 2.5s 后才返回。
想要编写 Nginx 模块,首先需要对 Nginx 模块中的源码以及相关的数据结构有所了解,还要知晓 Nginx HTTP 模块的调用流程。假设我要实现前面第三方模块Echo的最简单形式,即只输出相应的字符串即可。假定模块支持的指令名称还是 echo, 这个 echo 指令需要跟一个参数,即输出的字符串。我们需要做如下几步:
static ngx_command_t ngx_http_echo_commands[]={
{ ngx_string("echo"), /* 指令名称,利用ngx_string宏定义 */
NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1, /* 用在 location 指令块内,且有1个参数 */
ngx_http_echo, /* 处理回调函数 */
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_echo_loc_conf_t, ed), /* 指定参数读取位置 */
NULL },
ngx_null_command
};
static char *
ngx_http_echo(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_core_loc_conf_t *clcf;
/* 找到指令所属的配置块,这里我们限定echo指令的上下文环境只有location */
clcf=ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);
/* 指定处理的handler */
clcf->handler=ngx_http_echo_handler;
...
return NGX_CONF_OK;
}
static ngx_int_t
ngx_http_echo_handler(ngx_http_request_t *r)
{
...
/* 向用户发送相应包 */
return ngx_http_output_filter(r, &out);
}
/* Http context of the module */
static ngx_http_module_t ngx_http_echo_module_ctx={
NULL, /* preconfiguration */
NULL, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_http_echo_create_loc_conf, /* create location configration */
ngx_http_echo_merge_loc_conf /* merge location configration */
};
/* Module */
ngx_module_t ngx_http_echo_module={
NGX_MODULE_V1,
&ngx_http_echo_module_ctx, /* module context */
ngx_http_echo_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
完成以上几步,一个简易的自定义模块就算大功告成了。接下来我们动手完成第一个自定义的模块,将其编译进Nginx 二进制文件中并进行测试。
我们来完成一个简单的自定义 http 模块,来实现前面Echo模块的最简单形式,即使用指令输出 “hello, world” 字符串。首先新建一个目录echo-nginx-module,然后在目录下新建两个文件config和ngx_http_echo_module.c
[root@server echo-nginx-module]# pwd
/root/shencong/echo-nginx-module
[root@server echo-nginx-module]# ls
config ngx_http_echo_module.c
两个文件内容分别如下:
[root@server echo-nginx-module]# cat config
ngx_addon_name=ngx_http_echo_module
# 指定模块名称
HTTP_MODULES="$HTTP_MODULES ngx_http_echo_module"
# 指定模块源码路径
NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_echo_module.c"
[root@server echo-nginx-module]# cat ngx_http_echo_module.c
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
/* Module config */
typedef struct {
ngx_str_t ed;
} ngx_http_echo_loc_conf_t;
static char *ngx_http_echo(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
static void *ngx_http_echo_create_loc_conf(ngx_conf_t *cf);
static char *ngx_http_echo_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child);
/* 定义指令 */
static ngx_command_t ngx_http_echo_commands[]={
{ ngx_string("echo"), /* 指令名称,利用ngx_string宏定义 */
NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1, /* 用在 location 指令块内,且有1个参数 */
ngx_http_echo, /* 处理回调函数 */
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_echo_loc_conf_t, ed), /* 指定参数读取位置 */
NULL },
ngx_null_command
};
/* Http context of the module */
static ngx_http_module_t ngx_http_echo_module_ctx={
NULL, /* preconfiguration */
NULL, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_http_echo_create_loc_conf, /* create location configration */
ngx_http_echo_merge_loc_conf /* merge location configration */
};
/* Module */
ngx_module_t ngx_http_echo_module={
NGX_MODULE_V1,
&ngx_http_echo_module_ctx, /* module context */
ngx_http_echo_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
/* Handler function */
static ngx_int_t
ngx_http_echo_handler(ngx_http_request_t *r)
{
ngx_int_t rc;
ngx_buf_t *b;
ngx_chain_t out;
ngx_http_echo_loc_conf_t *elcf;
/* 获取指令的参数 */
elcf=ngx_http_get_module_loc_conf(r, ngx_http_echo_module);
if(!(r->method & (NGX_HTTP_HEAD|NGX_HTTP_GET|NGX_HTTP_POST)))
{
/* 如果不是 HEAD/GET/PUT 请求,则返回405 Not Allowed错误 */
return NGX_HTTP_NOT_ALLOWED;
}
r->headers_out.content_type.len=sizeof("text/html") - 1;
r->headers_out.content_type.data=(u_char *) "text/html";
r->headers_out.status=NGX_HTTP_OK;
r->headers_out.content_length_n=elcf->ed.len;
if(r->method==NGX_HTTP_HEAD)
{
rc=ngx_http_send_header(r);
if(rc !=NGX_OK)
{
return rc;
}
}
b=ngx_pcalloc(r->pool, sizeof(ngx_buf_t));
if(b==NULL)
{
ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "Failed to allocate response buffer.");
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
out.buf=b;
out.next=NULL;
b->pos=elcf->ed.data;
b->last=elcf->ed.data + (elcf->ed.len);
b->memory=1;
b->last_buf=1;
rc=ngx_http_send_header(r);
if(rc !=NGX_OK)
{
return rc;
}
/* 向用户发送相应包 */
return ngx_http_output_filter(r, &out);
}
static char *
ngx_http_echo(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_core_loc_conf_t *clcf;
clcf=ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);
/* 指定处理的handler */
clcf->handler=ngx_http_echo_handler;
ngx_conf_set_str_slot(cf,cmd,conf);
return NGX_CONF_OK;
}
static void *
ngx_http_echo_create_loc_conf(ngx_conf_t *cf)
{
ngx_http_echo_loc_conf_t *conf;
conf=ngx_pcalloc(cf->pool, sizeof(ngx_http_echo_loc_conf_t));
if (conf==NULL) {
return NGX_CONF_ERROR;
}
conf->ed.len=0;
conf->ed.data=NULL;
return conf;
}
static char *
ngx_http_echo_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child)
{
ngx_http_echo_loc_conf_t *prev=parent;
ngx_http_echo_loc_conf_t *conf=child;
ngx_conf_merge_str_value(conf->ed, prev->ed, "");
return NGX_CONF_OK;
}
这样一个第三方模块包就完成了,接下来我们要向之前使用第三方模块一样,将它编译进 Nginx,具体操作如下。
[root@server shencong]# cd nginx-1.17.6/
[root@server nginx-1.17.6]# ./configure --prefix=/root/shencong/nginx-echo --add-module=/root/shencong/echo-nginx-module
...
[root@server nginx-1.17.6] # make && make install
...
[root@server nginx-1.17.6]# cd ../nginx-echo/sbin/
[root@server sbin]# ./nginx -V
nginx version: nginx/1.17.6
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC)
configure arguments: --prefix=/root/shencong/nginx-echo --add-module=/root/shencong/echo-nginx-module
接下来,我们只要在 nginx.conf 中加入我们的指令,并给一个参数,就能看到我们自定义的输出了。
...
http {
...
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
location /test {
echo hello,world;
}
...
}
}
...
最后我们请求主机的80端口,URI=/test,浏览器输出"hello, world",说明我们的自定义模块成功了!
在 Nginx 基础架构介绍的最后,主要是介绍了 Nginx 的模块设计以及相应的模块用法。最后,我们简单给出了一个简单编写自己模块的案例作为本章的实战案例。希望这一节之后,大家能对 Nginx 的模块化设计有所了解,并有兴趣在模块的源码方向深入学习。
篇介绍比较基础的Nginx常用命令及配置。
#假设Nginx的安装目录为
/home/nginx/nginx/
#启动命令
/home/nginx/nginx/sbin/nginx -c /home/nginx/nginx/conf/nginx.conf
#状态检查
/home/nginx/nginx/sbin/nginx -t
#重新加载配置
/home/nginx/nginx/sbin/nginx -s reload
#关闭
#查询nginx主进程号
ps -ef | grep nginx
#从容停止
kill -QUIT 主进程号
#快速停止
kill -TERM 主进程号
#强制停止
kill -9 主进程号
#若nginx.conf配置了pid文件路径,如果没有,则在logs目录下
kill -信号类型 '/usr/local/nginx/logs/nginx.pid'
events事件驱动配置
events {
use epoll; #使用epoll类型的IO多路复用模型,性能比select高
worker_connections 204800; #Worker进程能够打开的最大并发连接数
accept_mutex on; #各个Worker进程通过锁来获取新连接
}
server虚拟主机配置
server {
listen 80;
server_name admin.cloudxue.com; #后台管理服务的域名前缀
location / {
default_type 'text/html';
charset utf-8;
echo "this is admin server";
}
}
server {
listen 80;
server_name file.cloudxue.com; #文件服务的域名前缀
location / {
default_type 'text/html';
charset utf-8;
echo "this is file server";
}
}
server {
listen 80 default;
server_name cloudxue.com *.cloudxue.com; #若未指定前缀,配置默认访问的虚拟主机
location / {
default_type 'text/html';
charset utf-8;
echo "this is default server";
}
}
多个虚拟主机之间根绝server_name匹配的优先级从高到低:
错误页面配置
error_page指令,该指令可用于http、server、location、if in location等上下文。
server {
listen 80;
server_name admin.cloudxue.com; #后台管理服务的域名前缀
root /usr/local/openresty/www;
location / {
default_type 'text/html';
charset utf-8;
echo "this is admin server";
}
#设置错误页面
#error_page 404 /404.html;
error_page 404=200 /404.html #防止404页面被劫持
error_page 500 502 503 504 /50x.html;
}
长链接配置
keepalive_timeout 75; #长链接有效时长,0表示禁用长链接,默认75秒
keepalive_requests 100; #一条长链接上允许被请求的资源的最大数量,默认100
访问日志配置
access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
http {
#先定义日志格式,名为为
log_format format_main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
#日志文件、日志访问格式
access_log logs/access_main.log format_main;
}
location路由规则配置
rewrite模块指令配置
Nginx的rewrite模块即ngx_http_rewrite_module标准模块,默认安装的模块。主要功能是对URI进行重写,然后再一次进行location匹配或者直接进行30X重定向返回给客户端。
set $variable value
#实例
set $a "foo";
set $b "$a, $a";
rewrite regrex replacement [flag];
#实例
location /download/ {
rewrite ^/download/(.*)/video/(.*)$ /view/$1/mp3/$2.mp3/ last;
rewrite ^/download/(.*)/audio/(.*)$ /view/$1/mp3/$2.rmvb/ last;
return 404;
}
location /view {
echo "uri: $uri ";
}
#访问如下地址
curl http://demo.cloudxue.com/download/1/video/10
#rewrite模块进行匹配后,占位变量$1的值为1, $2的值为10
uri: /view/1/mp3/10.mp3
如果同一个上下文中出现多个rewrite指令,匹配会按照rewrite指令出现的顺序先后依次进行下去,匹配成功后并不会终止,而是继续往下匹配,知道返回最后一个匹配为止。可以通过指令参数flag控制是否中途停止匹配,假设在location上下文中:
注意事项:
if (condition) {...}
#实例
location /if_demo {
if ($http_user_agent ~*"Firefox") { #匹配Firefox浏览器
return 403;
}
if ($http_user_agent ~*"Chrome") { #匹配Chrome浏览器
return 301;
}
if ($http_user_agent ~*"iphone") { #匹配iPhone手机
return 302;
}
if ($http_user_agent ~*"android") { #匹配安卓手机
return 404;
}
return 405; #其他浏览器默认规则
}
#格式1:返回响应的状态码和提示文字,提示文字可选
return code [text];
#格式2:返回响应的重定向状态码和重定向URL
return code URL;
#格式3:返回响应的重定向URL,默认的返回状态码是临时重定向302
return URL;
使用Ajax进行跨域请求时,浏览器会向跨域资源的服务端发送一个OPTION请求,用于判断实际请求是否安全或者判断服务端是否允许跨域访问,这种请求也叫预检请求。跨域访问的预检请求是浏览器自动发出的,用户程序不知情,如果不进行特殊的配置,那么客户端发出一次请求,在服务端会收到两个请求:一个是预检请求,一个是正式的请求。会比较影响性能,通常Nginx代理服务器对预检请求进行拦截,同时对预检请求设置比较长时间的有效期。
add_header Cache-Control no-store;
add_header Content-Encoding gzip;
add_header Content-Type 'text/html; charset=utf-8';
#实例
upstream zuul {
server "192.168.233.122:7799";
keepalive 1000;
}
server {
listen 80;
server_name nginx.server *.nginx.server;
default_type 'text/html';
charset utf-8;
#转发到上游服务器,但是‘OPTIONS’请求直接返回空
location / {
add_header Access-Control-Max-Age 1728000; #指定本次预检请求的有效期,单位秒,允许缓存该条回应20天,此期间内客户端不用发出另一条预检请求
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'Keep-Alive, User-Agent, X-Requested-With, \
If-Modified-Since, Cache-Control, COntent-Type,token';
return 204;
}
proxy_pass http://zuul/;
}
location /sequence_demo {
set $a foo;
echo $a;
set $a bar;
echo $a;
}
#访问测试:
curl http://cloudxue.com/sequence_demo
#响应
bar bar
#若按照请求处理阶段的先后次序排序
location /sequence_demo {
#rewrite 阶段的配置指令,执行在前面
set $a foo;
set $a bar;
#content阶段的配置指令,执行在后面
echo $a;
echo $a;
}
#所以以上输出为 bar bar
proxy_pass反向代理指令
位于ngx_http_proxy_module模块,注册在HTTP请求11个阶段的content阶段。
worker_processes 1;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
server {
listen 8080;
server_name localhost;
default_type 'text/html';
charset utf-8;
location / {
echo "-uri=$uri"
"-host=$host"
"-remote=$remote_addr"
"-proxy_add_x_forwarded=$proxy_add_x_forwarded_for"
"-http_x_forwarded_for=$http_x_forwarded_for";
}
}
server {
listen 80;
server_name localhost;
default_type 'text/html';
charset utf-8;
location / {
echo "默认根路径匹配:/";
}
#不带location前缀的代理类型
location /foo_no_prefix {
proxy_pass http://127.0.0.1:8080/;
}
#带location前缀的代理类型
location /foo_prefix {
proxy_pass http://127.0.0.1:8080;
}
#带部分URI路径的代理
location /foo_uri_1 {
proxy_pass http://127.0.0.1:8080/contextA/;
}
#带部分URI路径的代理
location /foo_uri_2 {
proxy_pass http://127.0.0.1:8080/context-A;
}
}
}
测试结果如下
? ~ curl http://127.0.0.1/foo_no_prefix/bar.html
-uri=/bar.html -host=127.0.0.1 -remote=127.0.0.1 -proxy_add_x_forwarded=127.0.0.1 -http_x_forwarded_for=? ~ curl http://127.0.0.1/foo_prefix/bar.html
-uri=/foo_prefix/bar.html -host=127.0.0.1 -remote=127.0.0.1 -proxy_add_x_forwarded=127.0.0.1 -http_x_forwarded_for=? ~ curl http://127.0.0.1/foo_uri_1/bar.html
-uri=/contextA/bar.html -host=127.0.0.1 -remote=127.0.0.1 -proxy_add_x_forwarded=127.0.0.1 -http_x_forwarded_for=? ~ curl http://127.0.0.1/foo_uri_2/bar.html
-uri=/context-A/bar.html -host=127.0.0.1 -remote=127.0.0.1 -proxy_add_x_forwarded=127.0.0.1 -http_x_forwarded_for=? ~
proxy_set_header请求头设置指令
在反向代理前,proxy_set_header指令能重新定义添加字段传递给代理服务的请求头。请求头的值可以包含文本、变量和它们的组合,格式如下
proxy_set_header head_field field_value;
该指令在发生反向代理之前,将保持在内置变量$remote_addr中的真实客户端地址保持到请求头中,通常请求头参数名为X-real-ip。
在Java端可以使用request.getHeader("X-real-ip")获取请求头的值,就可以拿到客户的真实IP。
由于在整个请求处理链条上可能不仅一次反向代理,可能会经过N次反向代理,为了获取整个转发记录,可以使用$proxy_add_x_forwarded_for内置变量,该值的第一个就是真实地址
为了不丢失信息,反向代理的设置如下:
location /hello {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_redirect off; #修改从上游被代理服务器传来的应答头中的Location和Refresh字段
}
以上配置,设置了Host、X-real-ip、X-Forwarded-For,分别将当前的目标主机、客户端IP、转发记录保存在请求头中。
当上游服务器返回的响应码是重定向301或者刷新302请求时,proxy_redirect指令可以重设HTTP头部的location或refresh字段值,off参数表示禁止所有的proxy_redirect指令,即反向代理时,禁止重定向。
作为Nginx的一大特色,若没有负载均衡,只有反向代理,那么其使用价值会大打折扣。Nginx在配置反向代理时,可以通过负载均衡机制配置一个上有服务器组。当组内某台机器宕机时,仍能维持系统可用,从而实现高可用。
Nginx的负载均衡配置主要用到upstream指令,其格式为:
upstream name {
server name address [parameters];
}
#上下文为http配置快,内部使用server指令定义组内的上游候选服务器
配置示例:
upstream zuul {
#名为upstream_zuul的共享内存区,大小为64k
zone upstream_zuul 64k;
#组内该机器的权重为5,最大并发连接数为500
server "192.168.223.121:7799" weight=5 max_conns=500;
#组内该机器的默认权重为1,同时设置20秒内失败2次,判定该服务器不可用
server "192.168.233.122:7799" fail_timeout=20s max_fails=2;
#后备服务
server "192.168.233.123:7799" backup;
}
upstream的负载分配方式
upstream backend {
#通过请求的$request_uri的hash值进行负载均衡
hash $request_uri consistent;
server 192.168.233.121;
server 192.168.233.122;
server 192.168.233.123;
}
*请认真填写需求信息,我们会在24小时内与您取得联系。