Yii urlmanager, append language on homepage

2019-09-19 22:29发布

问题:

i've wrote the following url rules:

            '<lang:(it|de|en|fr|es)>' => 'site/index',
            '<lang:(it|de|en|fr|es)>/search' => 'site/search',                              
            '<lang:(it|de|en|fr|es)>/<action:(page|logout)>/*' => 'site/<action>',                                                      
            '<lang:(it|de|en|fr|es)>/<controller:\w+>' => '<controller>/index',                
            '<lang:(it|de|en|fr|es)>/<controller:\w+>/<action:\w+>/*' => '<controller>/<action>',               
            '<lang:(it|de|en|fr|es)>/<module:\w+>/<controller:\w+>/<action:\w+>/*' => '<module>/<controller>/<action>',

and they work as i need, but one last problem.

With this rules i've achieved to attach the language to all url in this way: www.mysite.com/it/CONTROLLER/ACTION

The problem remain on the first visit, if a user wrote directly the website url in browser, he go to www.mysite.com AND NOT to www.mysite.com/userlanguage/ :(

In this way i've 3 duplicated urls for the home page that are:

 www.mysite.com
 www.mysite.com/userlanguage/
 www.mysite.com/index.php

and i need to redirect all of this to www.mysite.com/userlanguage/

My need is to have one different one page url for language.

Following the .htaccess

  RewriteEngine on
  #LOCAL


  RewriteBase /mydir/subdir/

  # if a directory or a file exists, use it directly
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d

  RewriteCond %{REQUEST_URI} !=/favicon.ico
  # otherwise forward it to index.php
  RewriteRule . /index.php

  AddDefaultCharset utf-8

Can anyone help me? Thank you

回答1:

If your default Controller is site/index, then you can do like this.

 public function actionIndex() {
        if(!isset($_GET['lang'])){
            $this->redirect(array('site/index','lang'=>'de')+$_GET); // 'de' is considered as default language
        }
        ---
    }