首页 > 解决方案 > 在 nginx 中,如何从 localhost 中获取从 localhost 发送的响应?

问题描述

我正在尝试从一个本地主机 php 页面(a.php)向同一本地主机发送一个 curl 请求到另一个 php 页面(b.php)。我对这个 nginx 东西完全陌生,真的需要帮助。

-----------
nginx.conf
-----------

worker_processes  1;

events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm index.php;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
        
        location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
    }
}
---------
start.bat
---------
@ECHO OFF
start C:\nginx-1.18.0\nginx.exe
start C:\php7.0.29\php-cgi.exe -b 127.0.0.1:9000 -c C:\php7.0.29\php.ini
ping 127.0.0.1 -n 1>NUL
echo Starting nginx
echo .
echo .
echo .
ping 127.0.0.1 >NUL
EXIT
------
a.php
------
<?php
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://localhost/b.php",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_SSL_VERIFYPEER => false,
  CURLOPT_SSL_VERIFYHOST => false,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET"
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
?>
------
b.php
------
<?php 
echo "Test";
exit();
?>
---------
error.log
---------
[error] 6596#9904: *2 upstream timed out (10060: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond) while reading response header from upstream, client: 127.0.0.1, server: localhost, request: "GET /a.php HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "localhost"
[error] 6596#9904: *13 upstream timed out (10060: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond) while reading response header from upstream, client: 127.0.0.1, server: localhost, request: "GET /b.php HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "127.0.0.1"

我已经使用上面的 nginx 配置,将请求从 a.php 页面发送到 b.php 页面。在浏览器上运行 a.php 后,它一直在加载,最后在很长一段时间后,它以“发生错误”作为响应,并且在检查时错误显示“504 错误”。

标签: phpnginxcurl

解决方案


你的批处理文件开始一切都不会像这样工作......

nginx 启动,但永远不会将控制权返回给脚本。php-fpm 没有启动。

要将 nginx 作为服务启动,start nginx请在安装文件夹中使用。

请注意,启动后 php-fpm 也不会返回。打开一个新的 CLI 并 ping localhost 或通过浏览器运行 a.php,届时应该可以工作了。

hth


推荐阅读