利用 VPS 搭建 Nginx 反向代理,繞過網路限制存取 Twitter 等境外服務。本文從 DNS 設定到 Nginx 配置、測試驗證全流程實作。
Client → DNS (t.jb51.net) → VPS IP → Nginx (port 80)
→ proxy_pass → twitter.com → 回應回傳給 Client
在域名註冊商後台新增 A 記錄:
主機記錄: t
記錄類型: A
記錄值: YOUR_VPS_PUBLIC_IP
TTL: 600 (或預設)
# /usr/local/nginx/conf/nginx.conf 或獨立 vhost 檔案
server {
listen 80;
server_name t.jb51.net;
location / {
proxy_pass https://twitter.com/; # 上游需 HTTPS
proxy_redirect off;
# 傳遞真實客戶端 IP
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
# WebSocket 支援(Twitter 使用)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# 超時調整
proxy_connect_timeout 30s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
# 可選:隱藏 Nginx 版本
server_tokens off;
}
# 語法檢查
/usr/local/nginx/sbin/nginx -t
# 輸出:syntax is ok / test is successful
# 平滑重載(不中斷連線)
kill -HUP $(cat /usr/local/nginx/logs/nginx.pid)
# 或 systemd 系統
systemctl reload nginx
# 本機測試
curl -I https://t.jb51.net
# 瀏覽器訪問 https://t.jb51.net 應顯示 Twitter 首頁
| 現象 | 原因 | 解決 |
|---|---|---|
| 502 Bad Gateway | 上游連線失敗/憑證驗證失敗 | 加入 proxy_ssl_verify off; 或配置信任 CA |
| 頁面樣式/JS 載入失敗 | 靜態資源域名不同 (abs.twimg.com 等) | 擴充 proxy_pass 至多域名,或使用 sub_filter 重寫連結 |
| 登入失敗/Session 異常 | Cookie Domain 不匹配 | proxy_cookie_domain twitter.com t.jb51.net; |
allow 1.2.3.4; deny all;limit_req_zone 防止濫用