nginx通過自定義http header 進行服務轉發


##  場景

由於小程序上線的需要,后台服務需要多版本並存。這里我們通過使用自定義的HTTP Header頭來實現。

nginx接收到的頭部為:

miniversion: 1.0

接收到此請求將會跳轉到新的url中。

核心:客戶端自定義的http header,在nginx的配置文件里能直接讀取到。

條件:header必須用減號“-”分隔單詞,nginx里面會轉換為對應的下划線“_”連接的小寫單詞。

這里面不建議使用“_”,會被nginx忽略掉。

所以我們為了省事,使用的是小寫字母全拼。可以使用"-" 會被轉化成“_”。多一事不如少一事,所以還是使用小寫字母。

## 修改nginx配置

主要的配置文件如下:

       server
        {
        listen       80;
        server_name  camp.h5.cc camp.cc camp.boss.cc;
        index index.jsp index.htm index.html index.do login.vm;
        charset utf-8;
        underscores_in_headers on;
        location ~ / {
                if ($http_miniversion = "1.0") {
                        proxy_pass http://Tall;

}


                        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_pass http://127.0.0.1:8080;
                }
        access_log  /data/logs/cc_com_access wwwlog;
        error_log   /data/logs/cc_com_error ;
        }

這里的自定義header前,需要加上http_下才能識別整個變量。

這里的Tall是我們的新版本,127.0.0.1,是我配置的一個配合測試的站點。

此站點的nginx配置文件如下:

cat mytest.com 
server {
    listen 8080;
    server_name localhost;

    root /var/www/html;
    index wx.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

underscores_in_headers on:

nginx是支持讀取非nginx標准的用戶自定義header的,但是需要在http或者server下開啟header的下划線支持:
比如我們自定義header為wx_unionid,獲取該header時需要這樣:$http_wx_unionid(一律采用小寫,而且前面多了個http_)

這里必須強調的一點是我們必須配置:

proxy_set_header  Host $host;
proxy_set_header  X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

否則會導致自定義header頭無效。

## 測試

echo "<h1>微信小程序測試平台</h1>" > /var/www/html/wx.html

 

這里如果我們直接使用瀏覽器,進行訪問,不傳遞.http header;結果如下:

 

 這里我們使用postman進行參數傳遞的測試:

 

 

 

可以看到,訪問到的是服務器的正常頁面。

## 附錄

nginx的主配置文件,僅供參考。

user www www;
worker_processes 8; 
error_log  /usr/local/nginx/logs/nginx_error.log  crit; 
pid        /usr/local/nginx/nginx.pid; 

#google_perftools_profiles /var/tmp/tcmalloc;

worker_rlimit_nofile 65535; 

events 
{  
         use epoll;  
         worker_connections 65535; 
}        

http 
{   
        include                                 mime.types;   
        default_type                            application/octet-stream;     
        charset                                 utf-8; 
    server_tokens                off;
        server_names_hash_bucket_size           128;
        client_header_buffer_size               4k; 
        large_client_header_buffers             4 4k;
        #client_max_body_size                    200m; 
        client_max_body_size                    1024m; 
        sendfile                                on;
        tcp_nopush                              on;
        tcp_nodelay                             on;
        keepalive_timeout                       60;
        open_file_cache                         max=204800 inactive=20s;
        open_file_cache_min_uses                1; 
        open_file_cache_valid                   30s;
        #proxy_connect_timeout                   300; 
        #proxy_send_timeout                      300; 
        #proxy_read_timeout                      300; 
    proxy_connect_timeout                   600;    
    proxy_send_timeout                      600;
    proxy_read_timeout                      600;    

        proxy_buffer_size                       16k; 
        proxy_buffers                           4 64k; 
        proxy_busy_buffers_size                 128k; 
        proxy_temp_file_write_size              128k; 
        gzip                                    on; 
        gzip_min_length                         1k; 
        gzip_buffers                            4 16k; 
        gzip_http_version                       1.1; 
        gzip_comp_level                         2; 
        gzip_types                              text/plain application/x-javascript text/css application/xml; 
        gzip_vary                               on; 
        # fastcgi_connect_timeout                 300;
        # fastcgi_send_timeout                    300;
        # fastcgi_read_timeout                    300;
    fastcgi_connect_timeout                 600;
    fastcgi_send_timeout                    600;
    fastcgi_read_timeout                    600;    

        fastcgi_buffer_size                     4k;
        fastcgi_buffers 8                       4k;
        fastcgi_busy_buffers_size               8k;
        fastcgi_temp_file_write_size            8k;
        fastcgi_cache_valid                     200 302 1h;
        fastcgi_cache_valid                     301 1d;
        fastcgi_cache_valid                     any 1m;
        fastcgi_cache_min_uses                  1;
        fastcgi_cache_use_stale                 error timeout invalid_header http_500;
        fastcgi_param                           SERVER_NAME     $host;
        server_name_in_redirect                 off;
        #add_header                              "X-UA-Compatible" "IE=EmulateIE8";
        upstream Tall {    
        server   192.168.150.13:9010;    
                }
        log_format  wwwlog  '$remote_addr - $remote_user [$time_local] "$request" '
        log_format  wwwlog  '$remote_addr - $remote_user [$time_local] "$request" '
        '$status $body_bytes_sent "$http_referer" '
        '"$http_user_agent" $http_x_forwarded_for';
include   vhosts/Tall/*;
include   vhosts/Ts/*;
include   vhosts/Tip/*;
}

 

參考鏈接:

http://www.ttlsa.com/nginx/nginx-proxy_set_header/

https://www.cnblogs.com/xiao987334176/p/11263649.html

 

最后付HTTPS完整配置文件,因為小程序需使用HTTPS

        server
        {
        listen       80;
        server_name  camp.h5.aixbx.com camp.aixbx.service camp.boss.aixbx.com;
        index index.jsp index.htm index.html index.do login.vm;
        charset utf-8;
        underscores_in_headers on;
        location ~ / {
        return 301 https://camp.h5.aixbx.com$request_uri;

}
        }
        server
        {
        listen       443 ssl;
        server_name  camp.h5.aixbx.com;
        index index.jsp index.htm index.html index.do login.vm;
        charset utf-8;
        underscores_in_headers on;
        ssl_certificate         /etc/pki/ssl/camp.h5.aixbx.com_nginx/camp.h5.aixbx.com.pem;
        ssl_certificate_key     /etc/pki/ssl/camp.h5.aixbx.com_nginx/camp.h5.aixbx.com.key;
        location ~ / {
                if ($http_miniversion = "1.0") {
                        proxy_pass http://Tall;

}


                        proxy_set_header  Host $host;
                        proxy_set_header  X-Real-IP  $remote_addr;
                        proxy_set_header X-Real-PORT $remote_port;
                        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                        proxy_pass http://127.0.0.1:8080;
                }
        access_log  /data/logs/aixbx_com_access wwwlog;
        error_log   /data/logs/aixbx_com_error ;
        }

 最后還贈送centos 6下的nginx啟動腳本,根據yum安裝之后生成的啟動腳本進行修改的。不知道為啥還用6,咱也不敢問。

#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:   - 85 15
# description:  Nginx is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /etc/nginx/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/nginx.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

nginx="/usr/local/nginx/sbin/nginx"
prog=$(basename $nginx)

sysconfig="/etc/sysconfig/$prog"
lockfile="/var/lock/subsys/nginx"
pidfile="/usr/local/nginx/${prog}.pid"

NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf"

[ -f $sysconfig ] && . $sysconfig


start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc -p $pidfile $prog
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    configtest_q || return 6
    stop
    start
}

reload() {
    configtest_q || return 6
    echo -n $"Reloading $prog: "
    killproc -p $pidfile $prog -HUP
    echo
}

configtest() {
    $nginx -t -c $NGINX_CONF_FILE
}

configtest_q() {
    $nginx -t -q -c $NGINX_CONF_FILE
}

rh_status() {
    status $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

# Upgrade the binary with no downtime.
upgrade() {
    local oldbin_pidfile="${pidfile}.oldbin"

    configtest_q || return 6
    echo -n $"Upgrading $prog: "
    killproc -p $pidfile $prog -USR2
    retval=$?
    sleep 1
    if [[ -f ${oldbin_pidfile} && -f ${pidfile} ]];  then
        killproc -p $oldbin_pidfile $prog -QUIT
        success $"$prog online upgrade"
        echo 
        return 0
    else
        failure $"$prog online upgrade"
        echo
        return 1
    fi
}

# Tell nginx to reopen logs
reopen_logs() {
    configtest_q || return 6
    echo -n $"Reopening $prog logs: "
    killproc -p $pidfile $prog -USR1
    retval=$?
    echo
    return $retval
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest|reopen_logs)
        $1
        ;;
    force-reload|upgrade) 
        rh_status_q || exit 7
        upgrade
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    status|status_q)
        rh_$1
        ;;
    condrestart|try-restart)
        rh_status_q || exit 7
        restart
        ;;
    *)
        echo $"Usage: $0 {start|stop|reload|configtest|status|force-reload|upgrade|restart|reopen_logs}"
        exit 2
esac

 ## 通過get參數判斷轉發

nginx 獲取請求頭,URL參數
獲取url參數
在 ngx_lua 中訪問 Nginx 內置變量 ngx.var.arg_PARAMETER 即可獲得GET參數PARAMETER的內容。
在 nginx配置中,通過$arg_PARAMETER 即可獲得GET參數PARAMETER的內容。
獲取請求頭
在 ngx_lua 中訪問 Nginx 內置變量 ngx.var.http_HEADER 即可獲得請求頭HEADER的內容。
在 nginx配置中,通過$http_HEADER 即可獲得請求頭HEADER的內容。

if ($arg_miniversion = "1.1"){
                      proxy_pass http://127.0.0.1:20032;
}

 

## Nginx返回大長度的JSON數據被截斷

1. 添加nginx參數,增加緩存字符串大小,在http字段中

proxy_buffer_size                       512k;
proxy_buffers                           16 512k;
proxy_busy_buffers_size                 512k;
proxy_temp_file_write_size              512k;

 

2. 遇到全新問題,原因是大文件會先緩存到/proxy-temp文件夾下面,然后再返回

Permission denied while reading upstream

修改文件夾的權限為nginx的用戶,根據你項目的實際情況來修改

chown -R www:www /usr/local/nginx/proxy-temp

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM