LOADING

nginx反向代理和ip透传 HowOldAreYou

–>

nginx反向代理和ip透传

nginx反向代理

反向代理:reverse proxy,可代理外网用户的请求到内部的指定web服务器,并将数据返回给用户
nginx除了可以在企业提供高性能的web服务之外,另外还可以将本身不具备的请求通过某种预定义的协议转发至其它服务器处理,不同的协议就是nginx服务器与其他服务器进行通信的一种规范
主要在不同的场景使用以下模块实现不同的功能:
  ngx_http_proxy_module: 将客户端请求以http协议转发至后端服务器
  ngx_http_fastcgi_module:将客户端对php请求以fastcgi协议转发至后端
  ngx_http_uwsgi_module:将客户端对Python请求以uwsgi协议转发至后端
  ngx_stream_proxy_module:将客户端请求以tcp协议转发至后端服务器
 

 

ngx_http_proxy_module

转发请求至另一台主机

proxy_pass URL;

1、proxy_pass后面路径不带uri时,会将location的uri传递(附加)给后端主机

server {
    ...
    server_name HOSTNAME;
    location /uri/ {
    proxy_pass http://host[:port]; 注意:最后没有/
    }
...
}

上面示例:http://HOSTNAME/uri –> http://host/uri ,功能类似 root;如果上面示例中有 /,即:http://host[:port]/ 此方式较少使用,意味着:http://HOSTNAME/uri –> http://host/ 即置换,功能类似 alias

2、proxy_pass后面的路径是一个uri时,其会将location的uri替换为proxy_pass的uri

server {
    ...
    server_name HOSTNAME;
    location /uri/ {
        proxy_pass http://host/new_uri/;
    }
    ...
}

http://HOSTNAME/uri/ –> http://host/new_uri/

3、如果location定义其uri时使用了正则表达式的模式,则proxy_pass之后必须不能使用uri; 用户请求时传递的uri将直接附加至后端服务器之后

server {
    ...
    server_name HOSTNAME;
    location ~|~* /uri/ {
    proxy_pass http://host; 不能加/ }
    ...
}

http://HOSTNAME/uri/ --> http://host/uri/    

实验一实现反向代理

两台服务器192.168.206.15作为nginx反代服务器,192.168.206.20作为httpd服务器;

nginx服务器配置

vim /etc/nginx/conf.d/proxy.conf
server { server_name www.testproxy.com; location
/dynamic/ { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://www.testdynamic.com; } }

httpd服务器配置

vim /etc/httpd/conf.d/server.conf 
<virtualHost *:80>
    ServerName www.testdynamic.com
    DocumentRoot "/apps/test.net/htdocs"
    <Directory "/apps/test.net/htdocs">
        options None
        AllowOverride None
        Require all granted
    </Directory>

</VirtualHost>
mkdir -p   /apps/test.net/htdocs
echo "for nginx proxy" > index.html

 

ip透传

proxy_set_header field value;

设定转发往后端主机的请求报文的请求首部的值; 
注意:因为其默认值是proxy_set_header Host $proxy_host;所以后端主机的访问日志中记录的IP都是代理服务器的。这样不便于通过日志,去判断服务访问情况。
Context: http, server, location

proxy_set_header X-Real-IP $remote_addr; 

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

请求报文的标准格式如下:
X-Forwarded-For: client1, proxy1, proxy2

实验一:实现ip透传

两台服务器192.168.206.15作为nginx反代服务器,192.168.206.20作为httpd服务器;

nginx配置

vim /etc/nginx/confi.d/proxy.conf 

server {
        server_name www.testproxy.com;
        location /dynamic/ {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_pass http://www.testdynamic.com;
        }

}

vim   /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.206.20 www.testdynamic.com

httpd服务器配置

/etc/httpd/conf/httpd.conf
 LogFormat "\"%{X-Forwarded-For}i\"  %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
vim /etc/httpd/conf.d/server.conf 
<virtualHost *:80>
    ServerName www.testdynamic.com
    DocumentRoot "/apps/test.net/htdocs"
    <Directory "/apps/test.net/htdocs">
        options None
        AllowOverride None
        Require all granted
    </Directory>

</VirtualHost>
mkdir -p   /apps/test.net/htdocs
echo "for nginx proxy" > index.html

 

反向代理缓存相关配置 

proxy_cache_path;

定义可用于proxy功能的缓存;Context:http
proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time]
[loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];
示例:在http配置定义缓存信息
  proxy_cache_path /var/cache/nginx/proxy_cache #定义缓存保存路径,proxy_cache会自动创建
  levels=1:2:2 #定义缓存目录结构层次,1:2:2 可以生成2^4×2^8×2^8=1048576个目录
  keys_zone=proxycache:20m #指内存中缓存的大小,主要用于存放key和metadata(如:使用次数)
  inactive=120s; #缓存有效时间
  max_size=1g; #最大磁盘占用空间,磁盘存入文件内容的缓存空间最大值

proxy_cache zone | off; 默认off

指明调用的缓存,或关闭缓存机制;Context:http, server, location

proxy_cache_key string;

缓存中用于“键”的内容
默认值:proxy_cache_key $scheme $proxy_host $request_uri;

proxy_cache_valid [code …] time;

定义对特定响应码的响应内容的缓存时长
定义在http{…}中
示例:

proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;

示例:在http配置定义缓存信息

proxy_cache_path /var/cache/nginx/proxy_cache levels=1:2:2 keys_zone=proxycache:20m inactive=120s max_size=1g; 
proxy_cache proxycache;
proxy_cache_key $request_uri;
proxy_cache_valid 200 302 301 1h;
proxy_cache_valid any 1m;
说明:proxycache:20m 指内存中缓存的大小,主要用于存放key和metadata(如:使用次数)max_size=1g 指磁盘存入文件内容的缓存空间最大值
调用缓存功能,需要定义在相应的配置段,如server{...};

proxy_cache_use_stale;

proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | off …
在被代理的后端服务器出现哪种情况下,可直接使用过期的缓存响应客户端

proxy_cache_methods GET | HEAD | POST …;

对哪些客户端请求方法对应的响应进行缓存,GET和HEAD方法总是被缓存

proxy_hide_header field;

用于隐藏后端服务器特定的响应首部,默认nginx在响应报文中不传递后端服务
器的首部字段Date, Server, X-Pad, X-Accel等
示例:
  proxy_hide_header Etag;

proxy_pass_header field;

默认nginx在响应报文中不传递后端服务器的首部字段Date, Server, X-Pad, X-Accel等参数,如果要传递的话则要使用 proxy_pass_header field声明将后端服务器返回的值传递给客户端。

ngx_http_headers_module模块

向代理服务器给客户端的响应报文添加自定义首部,或修改指定首部的值

add_header name value [always];

添加自定义首部
  add_header X-Via $server_addr;
  add_header X-Cache $upstream_cache_status;
  add_header X-Accel $server_name;

add_trailer name value [always];

添加自定义响应信息的尾部, 1.13.2版后支持

proxy_connect_timeout time;

  定义与后端服务器建立连接的超时时长,如超时会出现502错误,默认为60s,一般不建议超出75s

proxy_send_timeout time;

  对后端服务器send,将请求发送给后端服务器的超时时长;默认为60s

proxy_read_timeout time;

  从后端服务器read,等待后端服务器发送响应报文的超时时长,默认为60s

proxy_ignore_client_abort off;

  当客户端网络中断请求时,nginx服务器中断其对后端服务器的请求。即如果此项设置为on开启,则服务器会忽略客户端中断并一直等着代理服务执行返回,如果设置为off,则客户端中断后nginx也会中断客户端请求并立即记录499日志,默认为offngx_http_headers_module

proxy_http_version 1.0;

  用于设置nginx提供代理服务的HTTP协议的版本,默认http 1.0

proxy_headers_hash_bucket_size 128;

  当配置了 proxy_hide_header和proxy_set_header的时候,用于设置nginx保存HTTP报文头的hash表的上限

proxy_headers_hash_max_size 512;

  设置proxy_headers_hash_bucket_size的最大可用空间

server_namse_hash_bucket_size 512;

  server_name hash表申请空间大小

server_names_hash_max_size 512;

  设置服务器名称hash表的上限大小

ngx_http_fastcgi_module模块

转发请求到FastCGI服务器,不支持php模块方式

fastcgi_pass address;

  address为后端的fastcgi server的地址
  可用位置:location, if in location

fastcgi_index name;

  fastcgi默认的主页资源
  示例:fastcgi_index index.php;

fastcgi_param parameter value [if_not_empty];

  设置传递给 FastCGI 服务器的参数值,可以是文本,变量或组合

示例1:

1)在后端服务器先配置fpm server和mariadb-server
2)在前端nginx服务上做以下配置:

location ~* \.php$ {
  root /data/php; #$document_root 调用root目录
  fastcgi_pass 后端fpm服务器IP:9000;
  fastcgi_index index.php;
  fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  #fastcgi_param SCRIPT_FILENAME /data/php$fastcgi_script_name;
  #如果SCRIPT_FILENAME是绝对路径,则可以省略root /data/php;
  include fastcgi_params;
}

示例2:

通过/pm_status和/ping来获取fpm server状态信息

location ~* ^/(fpm_status|ping)$ {
  fastcgi_pass 后端fpm服务器IP:9000;
  fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
  include fastcgi_params;
}

fastcgi_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time][purger_threshold=time];

  定义fastcgi的缓存;
  path 缓存位置为磁盘上的文件系统路径
  max_size=size
    磁盘path路径中用于缓存数据的缓存空间上限
  levels=levels:缓存目录的层级数量,以及每一级的目录数量,levels=ONE:TWO:THREE
  示例:
    leves=1:2:2
  keys_zone=name:size
    k/v映射的内存空间的名称及大小
  inactive=time
    非活动时长

fastcgi_cache zone | off;

  调用指定的缓存空间来缓存数据,可用位置:http, server, location

fastcgi_cache_key string;

  定义用作缓存项的key的字符串
示例:fastcgi_cache_key $request_uri;

fastcgi_cache_methods GET | HEAD | POST …;

  为哪些请求方法使用缓存

fastcgi_cache_min_uses number;

  缓存项在inactive定义的非活动时间内至少要被访问到指定的次数方可被认作活动项

fastcgi_keep_conn on | off;

  收到后端服务器响应后,fastcgi服务器是否关闭连接,建议启用长连接

fastcgi_cache_valid [code …] time;

  不同的响应码各自的缓存时长

示例:
http {
  fastcgi_cache_path /var/cache/nginx/fcgi_cache levels=1:2:1 keys_zone=fcgicache:20m inactive=120s;

  server {
    location ~* \.php$ {

    fastcgi_cache fcgicache;
    fastcgi_cache_key $request_uri;
    fastcgi_cache_valid 200 302 10m;
    fastcgi_cache_valid 301 1h;
    fastcgi_cache_valid any 1m;
    } 
  }
}

ngx_http_upstream_module

  将多个服务器定义成服务器组,而由proxy_pass, fastcgi_pass等指令进行引用

upstream name { … }

  定义后端服务器组,会引入一个新的上下文
  默认调度算法是wrr
  Context: http
  upstream httpdsrvs {
    server …
    server…
    …
  }

server address [parameters];

  在upstream上下文中server成员,以及相关的参数;Context:upstream
  address的表示格式
    unix:/PATH/TO/SOME_SOCK_FILE
    IP[:PORT]
    HOSTNAME[:PORT]
  parameters
    weight=number
    权重,默认为1
    max_conns
      连接后端报务器最大并发活动连接数,1.11.5后支持
    max_fails=number
      失败尝试最大次数;超出此处指定的次数时,server将被标记为不可用,默认为1
    fail_timeout=time
      后端服务器标记为不可用状态的连接超时时长,默认10s
    backup
      将服务器标记为“备用”,即所有服务器均不可用时才启用
    down
      标记为“不可用”,实现灰度发布

    ip_hash
      源地址hash调度方法
    least_conn
      最少连接调度算法,当server拥有不同的权重时其为wlc,当所有后端主机连接数相同时,则使用wrr,适用于长连接
    hash key [consistent]
       基于指定的key的hash表来实现对请求的调度,此处的key可以直接文本、变量或二者组合
      作用:将请求分类,同一类请求将发往同一个upstream server,使用consistent参数,将使用ketama一致性hash算法,适用于后端是Cache服务器(如varnish)时使用
      hash $request_uri consistent;
      hash $remote_addr;
      hash $cookie_name; #key为name的cookie
    kepalive 连接数N;
      为每个worker进程保留的空闲的长连接数量,可节约nginx端口,并减少连接管理的消耗
配置示例

upstream dynamic {
    zone upstream_dynamic 64k;

    server backend1.example.com      weight=5;
    server backend2.example.com:8080 fail_timeout=5s slow_start=30s;
    server 192.0.2.1                 max_fails=3;
    server backend3.example.com      resolve;
    server backend4.example.com      service=http resolve;

    server backup1.example.com:8080  backup;
    server backup2.example.com:8080  backup;
}

server {
    location / {
        proxy_pass http://dynamic;
        health_check;
    }
}
upstream webserver {
    server 192.168.206.20      weight=1;
    server 192.168.206.10  fail_timeout=5s;
}

server {
    location / {
        proxy_pass http://webserver;
    }
}

 

 
 

原文链接:https://www.cnblogs.com/wxxjianchi/p/13627682.html
本文来源 互联网收集,文章内容系作者个人观点,不代表 本站 对观点赞同或支持。如需转载,请注明文章来源,如您发现有涉嫌抄袭侵权的内容,请联系本站核实处理。

© 版权声明

相关文章