Nginx两种反向代理方式:fastcgi,upstreaming

1 简介

Nginx反向代理可以通过两种方式实现,fastcgi和upstreaming

2 fastcgi

该部分以PHP为例介绍通过fastcgi实现反向代理。
fastcgi相关介绍见这里
首先安装Nginx和PHP环境。建议使用https://lnmp.org/ 。一键安装,非常方便。安装完成后,找到配置文件/usr/local/nginx/conf/nginx.conf。在配置文件中找到include enable-php.conf;这一行。在enable-php.conf文件中定义了Nginx中的location配置,内容如下

  • enable-php.conf中的内容
location ~ [^/]\.php(/|$)*
{
try_files $uri =404;
fastcgi_pass  unix:/tmp/php-cgi.sock; #指定FastCGI服务器监听端口与地址,可以是本机或者其它
fastcgi_index index.php;
include fastcgi.conf; #fastcgi配置项
}
  • fastcgi.conf中的内容
fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;
**

通过以上配置就可以通过Ningx的web服务访问PHP了。

  • 其它语言的fastcgi
    • Python:见Flask http://flask.pocoo.org/docs/0.12/deploying/fastcgi/
    • C/C++:http://www.cnblogs.com/skynet/p/4173450.html

3 upstream

通过upstream可以实现反向代理,下面将以一个实际的例子演示如何配置upstream。

  • 用Python的Flask建立一个简单的Http服务,见http://docs.jinkan.org/docs/flask/quickstart.html#a-minimal-application中的hello word。代码如下
# =====hello.py
from flask import Flask
app = Flask(__name__)
@app.route('/debug_upstream')
def hello_world():
    return 'Hello World!'
if __name__ == '__main__':
    app.run()

在命令行下执行python ./hello.py。在浏览器中输入localhost:5000/debug_upstream,会在浏览器中返回Hello Word

  • 通过nginx的upstream实现反向代理
    在nginx的配置文件nginx.conf中,配置upstream和server信息,如下
user  www www;
worker_processes auto;
error_log  /home/wwwlogs/nginx_error.log  crit;
pid        /usr/local/nginx/logs/nginx.pid;
google_perftools_profiles /tmp/tcmalloc;
#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 51200;
events
    {
        use epoll;
        worker_connections 51200;
        multi_accept on;
    }
http
    {
        include       mime.types;
        default_type  application/octet-stream;
        server_names_hash_bucket_size 128;
        client_header_buffer_size 32k;
        large_client_header_buffers 4 32k;
        client_max_body_size 50m;
        sendfile   on;
        tcp_nopush on;
        keepalive_timeout 60;
        tcp_nodelay on;
        fastcgi_connect_timeout 300;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
        fastcgi_buffer_size 64k;
        fastcgi_buffers 4 64k;
        fastcgi_busy_buffers_size 128k;
        fastcgi_temp_file_write_size 256k;
        gzip on;
        gzip_min_length  1k;
        gzip_buffers     4 16k;
        gzip_http_version 1.1;
        gzip_comp_level 2;
        gzip_types     text/plain application/javascript application/x-javascript text/javascript text/css application/xml application/xml+rss;
        gzip_vary on;
        gzip_proxied   expired no-cache no-store private auth;
        gzip_disable   "MSIE [1-6]\.";
        #limit_conn_zone $binary_remote_addr zone=perip:10m;
        ##If enable limit_conn_zone,add "limit_conn perip 10;" to server section.
        server_tokens off;
        #log format
        log_format  access  '$remote_addr - $remote_user [$time_local] "$request" '
             '$status $body_bytes_sent "$http_referer" '
             '"$http_user_agent" $http_x_forwarded_for';
        access_log off;
    #新增加的upstream配置
        upstream  debug_server
        {
            server 127.0.0.1:5000;
        }
#新增加的server配置
server
    {
        listen 81 default_server;
        location /debug_upstream
        {
            proxy_pass http://debug_server;
        }
    }

server
    {
        listen 80 default_server;
        #listen [::]:80 default_server ipv6only=on;
        server_name www.lnmp.org;
        index index.html index.htm index.php;
        root  /home/wwwroot/default;

        #error_page   404   /404.html;
        include enable-php.conf;

        location /nginx_status
        {
            stub_status on;
            access_log   off;
        }

        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
        {
            expires      30d;
        }

        location ~ .*\.(js|css)?$
        {
            expires      12h;
        }

        location ~ /\.
        {
            deny all;
        }

        access_log  /home/wwwlogs/access.log  access;
    }
include vhost/*.conf;
}

保存以上配置文件,并执行sudo nginx -s reload,重新加载配置文件信息。
然后在浏览器中输入localhost:51/debug_upstream,亦可得到Hello Word

  • 注意:在配置nginx的upstream中,proxy_pass中location /后面的配置一定要和需要需要负载均衡的Http服务中的主机后面的配置信息一致,例如在本例中用Flask实现的Http服务为localhost:5000/debug_upstream,即主机localhost:5000后面的配置是debug_upstream,所以nginx中的proxy_pass中/后面的配置也要为debug_upstream,否则就会报404错。

你可能感兴趣的:(服务端架构)