URL routing for Localization

I am trying to make my application’s url like www.example.org/home where the default language is IT(Italian) and for English like www.example.org/en/home in CakePHP3. This is working fine with www.example.org/it/home, but I want remove it since IT is default language. How can I get this to be done?

Something like this in your routes.php:

Router::scope('/en',['language' => 'en'], function ($routes) {
    //...
    $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
    $routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
    $routes->fallbacks('InflectedRoute');
});

Router::scope('/', function ($routes) {
    //...
    $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
    $routes->connect('/pagine/*', ['controller' => 'Pages', 'action' => 'display']);
    $routes->fallbacks('InflectedRoute');
});

In view create links like:

echo $this->Html->link(__('Home), ['language' => I18n::locale(),'controller' => 'Pages', 'action' => 'display','home'], ['class' => 'navbar-brand', 'escape' => false]);

That is working fine but the urls are not getting prefixed for foreign language. Like once I switched to en language the links are still www.example.org/home and it redirecting to Italian.

Create links like:

<?= $this->Html->link(__('Home), ['language' => I18n::locale(),'controller' => 'Pages', 'action' => 'display','home'], ['class' => 'navbar-brand', 'escape' => false]); ?>

But in general the correct approach is to use the language prefix in the multilingual website for all language, in your case also in Italian.

I think I should follow the correct approach thanks :slight_smile:

You could also use I18nRoute from this plugin: https://github.com/ADmad/cakephp-i18n#using-the-i18nroute
It does all of the magic for you.

1 Like