Proxy
由于 Swoole Server
對 HTTP
協議的支持并不完整,建議僅將 EasySwoole
作為后端服務,并且在前端增加 Nginx
或 Apache
作為代理,參照下面的例子添加轉發規則
Nginx
server {
listen 80;
server_name local.swoole.com;
root /data/wwwroot/;
location / {
proxy_http_version 1.1;
proxy_set_header Connection "keep-alive";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
if (!-f $request_filename) {
proxy_pass http://127.0.0.1:9501;
}
}
}
具體部署時的 nginx
代理配置,還可參考 Deploy-Nginx 章節。
代理之后,可通過 $request->getHeaderLine('x-real-ip')
獲取客戶端真實ip
<?php
// 控制器中獲取客戶端真實ip的方法
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\Http\AbstractInterface\Controller;
class Base extends Controller
{
/**
* 獲取用戶的真實IP
* @param string $headerName 代理服務器傳遞的請求頭名稱
* @return string|null
*/
protected function clientRealIP(string $headerName = 'x-real-ip'): ?string
{
$server = ServerManager::getInstance()->getSwooleServer();
$client = $server->getClientInfo($this->request()->getSwooleRequest()->fd);
$clientAddress = $client['remote_ip'];
$xri = $this->request()->getHeaderLine($headerName);
$xff = $this->request()->getHeaderLine('x-forwarded-for');
if ($clientAddress === '127.0.0.1') {
if (!empty($xri)) { // 如果有 xri 則判定為前端有 NGINX 等代理
$clientAddress = $xri;
} elseif (!empty($xff)) { // 如果不存在 xri 則繼續判斷 xff
$clientAddress = $xff;
}
}
return $clientAddress;
}
}
Apache
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
# RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L] fcgi 下無效
RewriteRule ^(.*)$ http://127.0.0.1:9501/$1 [QSA,P,L]
# 請開啟 proxy_mod proxy_http_mod request_mod
</IfModule>
其他
-
QQ 交流群
- VIP 群 579434607 (本群需要付費 599 元)
- EasySwoole 官方一群 633921431(已滿)
- EasySwoole 官方二群 709134628(已滿)
- EasySwoole 官方三群 932625047(已滿)
- EasySwoole 官方四群 779897753(已滿)
- EasySwoole 官方五群 853946743(已滿)
- EasySwoole 官方六群 524475224(已滿)
- EasySwoole 官方七群 1016674948
-
商業支持:
- QQ 291323003
- EMAIL admin@fosuss.com
-
作者微信
-
捐贈 您的捐贈是對
EasySwoole
項目開發組最大的鼓勵和支持。我們會堅持開發維護下去。 您的捐贈將被用于:- 持續和深入地開發
- 文檔和社區的建設和維護
-
EasySwoole
的文檔使用EasySwoole 框架
提供服務,采用MarkDown 格式
和自定義格式編寫,若您在使用過程中,發現文檔有需要糾正 / 補充的地方,請fork
項目的文檔倉庫,進行修改補充,提交Pull Request
并聯系我們。