Guide Exposing a Local Laravel Server with Subdomains for Mobile Testing

This guide details how to expose a local Laravel development server, specifically one that uses subdomain routing (e.g., `api.localhost`), to the public internet for testing with a mobile application.

Guide: Exposing a Local Laravel Server with Subdomains for Mobile Testing

This guide details how to expose a local Laravel development server, specifically one that uses subdomain routing (e.g., api.localhost), to the public internet for testing with a mobile application.

The Scenario

When developing a mobile application that communicates with a backend API, you often run the API on your local machine. For the mobile app (running on a physical device or emulator) to reach this local server, the server must be accessible from the public internet.

  • Backend: A Laravel application running locally.
  • Local Endpoint: http://api.localhost:8000
  • Mobile App: An Android or iOS app that needs to send requests to the backend.

Tools like ngrok are popular for this, but if you need a free and simple alternative, localtunnel is an excellent choice.

The Challenge: Subdomain Routing

Our Laravel application is configured to handle API requests through a specific subdomain. The routing logic checks that the request’s Host header starts with api..

A standard attempt to use localtunnel might look like this:

  1. Install localtunnel:

    npm install -g localtunnel
  2. Start the Laravel server:

    php artisan serve --port=8000
  3. Start localtunnel:

    lt --port 8000

This will provide a public URL, like https://thick-pumas-take.loca.lt. However, when you use this URL in your mobile app, the requests will fail.

Why? By default, localtunnel forwards the request to localhost:8000. The Host header seen by your Laravel application is localhost, not api.localhost. Because the host does not match the api. subdomain requirement, the router fails to direct the request to your API routes.

The Solution: The --local-host Flag

localtunnel provides a simple flag to solve this exact problem: --local-host. This option tells localtunnel what Host header to use when forwarding the request to your local server.

Correct Steps

  1. Stop any running processes. Make sure both php artisan serve and lt are stopped.

  2. Start your Laravel server as usual.

    php artisan serve --port=8000
  3. Start localtunnel with the --local-host flag.

    lt --port 8000 --local-host api.localhost

Now, when a request is made to your new public loca.lt URL, localtunnel will forward it to your local machine on port 8000 and set the Host header to api.localhost. Your Laravel application will see the request exactly as it expects and route it correctly.

You can now use the new public URL provided by this command in your mobile application for successful testing.