'Laravel route() returning naked IP address instead of domain

Didn't catch this on my local machine but I've noticed some of my pages returning the naked IP address of my web server instead of the domain name. Example:

route('homepage') will sometimes return 192.XX8.X.2XX or 192.XX8.X.2XX/index.php or domain.com/index.php. My pages are cached upon the first visit and there's a rough 50% chance the things will come out weird for all URLs on the page.

Is there an explanation for this weird behavior and how would I fix it? It's quite a concern since Googlebot is listing three additional duplicate copies of my site.

Note: I'm also using the LaravelLocalization package for my routes: https://github.com/mcamara/laravel-localization

I'm also running this app under Laravel Forge (Nginx)



Solution 1:[1]

I understand, the question is very old, but I've had same problem and found the solution. (it can help someone)

Open file RouteServiceProvider on this path: app/Providers/RouteServiceProvider.php

Look for function mapWebRoutes. Now we have to add caller domain with config from our environment

protected function mapWebRoutes()
{
    Route::middleware('web')
        ->namespace($this->namespace)
        ->domain(\Config::get('app.url', null))
        ->group(base_path('routes/web.php'));
}

During building the url based on route - system tries to get local variable domain in current route, if it found - the domain should apply immediately. But if property undefined - go to Symfony route module.

PS: Don't forget to set APP_URL in your .env file. Example:

APP_URL=https://mysimpledomain.ua

Solution 2:[2]

I had gread success using

\URL::forceRootUrl(\Config::get('app.url'));

in RouteServiceProvider.php on boot().

Solution 3:[3]

This is most likely down to your nginx configuration. If you only have your app configured on the server then it will act as the default. When you visit the server directly by it's IP address (or any other domain that links to your server) then nginx will serve the laravel app.

There are many approaches to deal with this. I would suggest to either configure a default for the server. This could be just a html page saying "congratulations you've reached the server" or something similar. The other is just reconfigure you app's nginx file to redirect anything that's not the correct domain to the domain name for you app.

server {
    if ($host != example.com) {
        return 301 https://example.com$request_uri;
    }
    listen 80;
    server_name example.com;
}

More about how nginx processes a request here: http://nginx.org/en/docs/http/request_processing.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stephan Vierkant
Solution 2 Felix D.
Solution 3 forsvunnet