React frontend routing interferes with PHP ssh2_connect function returning 503 error

Hi everyone, I need some help with a weird issue I’m facing.

I’m building a system where I have a React app running alongside a PHP backend. The PHP backend has multiple API endpoints that work perfectly fine, except for one specific service that uses ssh2_connect.

Here’s my problematic PHP code:

case 'remote_connection':
    $server_port = 22;
    $message = 'connection_test';
    $ssh_session = ssh2_connect($remote_host, $server_port);
    if(!$ssh_session) die("Failed to establish connection");

Whenever this code runs, instead of getting my expected response, I get the React app’s main HTML page returned. All my other API calls work fine, but this ssh2_connect one behaves differently.

My setup is pretty standard. I have a React app created with create-react-app running on port 3000. The backend PHP files are in the same project structure. I’m using React Router v6 for handling frontend routes.

The weird part is that when I comment out the ssh2_connect line, everything works as expected. But as soon as I include that function call, React Router seems to take over and serves the index.html instead of my API response.

I can access other endpoints like http://localhost:3000/api/users without any issues, but http://localhost:3000/api/remote_connection returns HTML instead of JSON.

I suspect this might be related to how React Router handles unknown routes, but I can’t figure out why only the ssh2_connect function triggers this behavior. When I run the PHP file directly from command line, it works perfectly.

Has anyone encountered something similar? Any ideas on what might be causing this conflict between ssh2_connect and React Router?

that’s really weird! have you looked at your server logs? maybe ssh2_connect is timing out or failing, causing the server to fall back to the react app instead of sending the api response. can you debug it a bit?

I hit the same issue with SSH operations triggering fallback routing. This happens when ssh2_connect fails silently or times out - PHP’s error handling doesn’t catch it properly. Your web server’s probably got a catch-all rule that serves the React app when requests don’t return proper HTTP responses. Wrap your ssh2_connect call in proper error handling and set explicit HTTP headers before attempting the connection. Also check if SSH2 extension is loaded in your PHP environment - run extension_loaded('ssh2') to verify. Since it works via command line but not through the web server, you’re likely dealing with either a permissions issue or the extension isn’t available in your web PHP config.

your webserver’s redirecting failed requests to react’s index.html. ssh2_connect is probably crashing or throwing an error, then apache/nginx catches it and serves the spa fallback. check your .htaccess or server config for those fallback rules.