简体   繁体   中英

HTACCESS REWRITE: Ignore Language code and add index.php to the url without changing it

I am using the following rules to redirect the url with language code(en, fr, etc.) to url without it but added index.php before any segments. But it doesn't work as expected.

I need the index.php because I am using codeigniter, a php framework.

The url users visit:

http://www.example.com/en/home

The location they actually go to:

http://www.example.com/index.php/home

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(en|fr)/(.*)$ index.php/$2 [NC,L]  

The redirection works if I use the following rule, but I don't want to change the url.

RewriteRule ^(en|fr)/(.*)$ http://www.example.com/index.php/index.php/$2 [NC,L] 

You didn't need index.php in the url. But for that, it depend of your configuration server.

In most cases, my team and me use the following htaccess and we edit the configuration file (config.php) to set the index_page to '' because your htaccess know perfectly doing the stuff. But, for the routes, let codeigniter doing that for you.

#.htaccess file
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|images|robots\.txt|css|docs|js|system)
RewriteRule ^(.*)$ index.php/$1 [L]

And for your application/config/config.php file

/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = ''; // at the place of : 'index.php';

At the end, you should set some basics routes :

// application/config/config.php file
$route['default_controller'] = 'Home';
// other routes here
$route['^(en|fr)/(.+)$'] = "$2";
$route['^(en|fr)$'] = $route['default_controller'];

Take care, the position of your routes is important. (The most precise to the less)

I encourage you to read the official url documentation and the official regex routing documentation and have a look at this i18n library (Work on codeigniter 2 and 3 without problems)

I hope it will help you, and others, for understanding routes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM