接入微信公眾號開發時,第一步總是填寫伺服器配置,之後才能依接口文檔實現業務邏輯。麻煩之處在於,微信公眾號只認 80 埠,別的埠一律不通過。可業務上又常常要求:同一個公眾號域名底下,同時掛兩個都需要微信授權的專案。
這個矛盾用 Nginx 反向代理就能化解。做法是讓 Nginx 對外只暴露 80 埠,內部則依請求路徑的不同,把流量分派到各自的上游服務。

編輯 /usr/local/nginx/conf/nginx.conf:

worker_processes 4;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
gzip on;
gzip_min_length 1k;
gzip_buffers 16 64k;
gzip_http_version 1.1;
gzip_comp_level 6;
gzip_types text/plain application/x-javascript text/css application/xml application/javascript;
gzip_vary on;
# 指向專案一
upstream backend1 {
server 192.168.1.1:8081;
}
# 指向專案二
upstream backend2 {
server 192.168.1.1:8082;
}
proxy_cache_path /tmp/cache levels=1:2 keys_zone=cache:128m inactive=1d max_size=1G;
include vhosts/*;
}
接著編輯 /usr/local/reverse_proxy_nginx/conf/nginx.conf:

worker_processes 2;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
access_log /home/nginx_log/reverse_proxy_no1_access.log;
sendfile on;
keepalive_timeout 65;
upstream backend1 {
server 192.168.1.1:8081;
}
upstream backend2 {
server 192.168.1.1:8082;
}
proxy_cache_path /tmp/cache levels=1:2 keys_zone=cache:128m inactive=30m max_size=1G;
server {
listen 8081;
server_name h5.xxxx.com;
location / {
proxy_pass https://backend1;
proxy_redirect off;
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_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_max_temp_file_size 0;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
add_header Nginx-Res "https://backend1";
}
# 路徑以 h5 開頭的請求,轉給專案二
location ~ ^/(h5)(.*)$ {
proxy_pass https://backend2;
proxy_redirect off;
proxy_set_header Host $host;
proxy_cache cache;
proxy_cache_valid 200 302 1d;
proxy_cache_valid 301 1d;
proxy_cache_valid any 1m;
expires 1h;
add_header Nginx-Res "https://backend2";
proxy_ignore_headers "Cache-Control" "Expires" "Set-Cookie";
add_header Nginx-Cache "$upstream_cache_status";
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# 靜態資源走快取
location ~ .*\.(gif|jpg|png|css|js|ico)(.*) {
proxy_pass https://backend1;
proxy_redirect off;
proxy_set_header Host $host;
proxy_cache cache;
proxy_cache_valid 200 302 30d;
proxy_cache_valid 301 1d;
proxy_cache_valid any 1m;
expires 30d;
proxy_ignore_headers "Cache-Control" "Expires" "Set-Cookie";
add_header Nginx-Res "https://backend1";
add_header Nginx-Cache "$upstream_cache_status";
}
}
}
只要請求路徑中包含 h5,流量便會被導向 8081 那組服務,而對使用者、對微信伺服器而言,看到的仍然是 80 埠。於是兩個專案可以在同一個域名並存,微信授權登入等功能都能正常跑通。
實作時有兩點值得留意:一是 proxy_set_header Host $host 必須保留,微信授權回跳依賴正確的 Host;二是快取相關的 proxy_ignore_headers 會忽略後端的快取控制標頭,若後端有登入態頁面,記得排除在快取之外。