本篇文章給大家聊聊PHP-FPM、Nginx、FastCGI三者之間的關系,以及 Nginx 反向代理和負載均衡的配置。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有所幫助。
PHP-FPM,Nginx,FastCGI 之間的關系
FastCGI 是一個協議,它是應用程序和 WEB 服務器連接的橋梁。Nginx 并不能直接與 PHP-FPM 通信,而是將請求通過 FastCGI 交給 PHP-FPM 處理。
location ~ .php$ { try_files $uri /index.php =404; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_buffers 16 16k; fastcgi_buffer_size 32k; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; }
這里 fastcgi_pass 就是把所有 php 請求轉發給 php-fpm 進行處理。通過 netstat 命令可以看到,127.0.0.1:9000 這個端口上運行的進程就是 php-fpm.
Nginx 反向代理
Nginx 反向代理最重要的指令是 proxy_pass,如:
location ^~ /seckill_query/ { proxy_pass http://ris.filemail.gdrive:8090/; proxy_set_header Host ris.filemail.gdrive; } location ^~ /push_message/ { proxy_pass http://channel.filemail.gdrive:8090/; proxy_set_header Host channel.filemail.gdrive; } location ^~ /data/ { proxy_pass http://ds.filemail.gdrive:8087/; proxy_set_header Host ds.filemail.gdrive; }
通過 location 匹配 url 路徑,將其轉發到另外一個服務器處理。
通過負載均衡 upstream 也可以實現反向代理。
Nginx 負載均衡
介紹一下 upstream 模塊:
負載均衡模塊用于從”upstream”指令定義的后端主機列表中選取一臺主機。nginx先使用負載均衡模塊找到一臺主機,再使用upstream模塊實現與這臺主機的交互。
負載均衡配置:
upstream php-upstream { ip_hash; server 192.168.0.1; server 192.168.0.2; } location / { root html; index index.html index.htm; proxy_pass http://php-upstream; }
該例定義了一個 php-upstream 的負載均衡配置,通過 proxy_pass 反向代理指令應用這個配置。這里用的 ip_hash 算法,負載均衡的算法有多種,就不一一列舉了。
負載均衡也可以用在 fastcgi_pass 上。
如:
fastcgi_pass http://php-upstream
問題
反向代理和負載均衡是什么關系
反向代理和負載均衡這兩個詞經常出現在一起,但他們實際上是不同的概念,負載均衡它