i18n URIs with CI Routing or mod_rewrite - .htaccess

I'm trying to clean up my URIs on a multi-language CI site by changing the segment containing the language name to just the two-character language code.
Currently, my URIs look like this:
http://example.com // Home (English)
http://example.com/english/home // Home (English)
http://example.com/home // 404 (should go to english/home)
http://example.com/sv // 404 (should go to swedish/home)
http://example.com/swedish/home // Home (Swedish)
http://example.com/sv/home // 404 (should go to swedish/home)
I have experimented both with application/config/routes.php and .htaccess, but I feel I'm not making much progress. Which should I be using? How can I achieve my desired results?
As it stands, my files look like this:
// .htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /example/index.php/$1 [L]
// application/config/routes.php (minus docs)
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$route['default_controller'] = "pages/view/home";
$route['([a-z]+)/([a-z]+)'] = "pages/view/$2";
?>
// application/controllers/page
<?php
class Pages extends CI_Controller {
public function __construct() {
parent::__construct();
$this->language = $this->uri->segment(1);
}
public function view ($page = 'home') {
if (!file_exists('application/views/pages/'.$page.'.php'))
show_404();
$data['title'] = $page;
$this->lang->load('general',$this->language);
$this->load->view('templates/header', $data);
$this->load->view('pages/'.$page, $data);
$this->load->view('templates/footer', $data);
}
}
?>

Try this in routes.php:
$route['default_controller'] = "pages/view/home";
$route['(en|sv)'] = 'pages/view/home';
$route['(en|sv)/([a-z]+)'] = 'pages/view/$2';
Controller constructor:
function __construct(){
parent::__construct();
$this->lang_array = array('en' => 'english', 'sv' => 'swedish');
$this->current_lang = $this->uri->segment(1, 'en');
}
View function:
public function view ($page = 'home') {
$lang_folder = $this->lang_array[$this->current_lang];
// $lang_folder will be 'english' by default
// other stuff
$this->lang->load('general', $lang_folder);
}

Above your current rules, add these:
# You already had this one
RewriteEngine On
RewriteRule ^home(.*)$ /english/home$1 [L]
RewriteRule ^sv(/home)?(.*)$ /swedish/home$1 [L]
Then the ones you already have:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /kappahl-hilys/index.php/$1 [L]

You can also:
In a first Hook(pre_system) file, detect the language in URI:
<?php
class Lang_uri {
public function run() {
$languages = array('fr', 'en');
//try to find language in $_SERVER['REQUEST_URI']
foreach($languages as $lang)
{
if(strpos($_SERVER['REQUEST_URI'], '/'.$lang)===0)
{
//Store language founded
define('URI_LANG', $lang);
//Delete it, codeigniter will don't know is exists !
$_SERVER['REQUEST_URI'] = substr_replace($_SERVER['REQUEST_URI'], '', strpos($_SERVER['REQUEST_URI'], '/'.$lang)+1, strlen($lang)+1);
break;
}
}
if(!defined('URI_LANG'))
define('URI_LANG', 'fr');
}
}
Now in an another hook file(pre_controller) set language config item
class Set_language {
public function set() {
global $CFG;
$CFG->set_item('language', str_replace(array('en', 'fr'), array('english', 'french'), URI_LANG));
}
}
That's all.
http://site.com/fr/home and http://site.com/home will work as same..
For more infos about CI Hook: http://codeigniter.com/user_guide/general/hooks.html
Sorry for my poor english..

Related

URL Rewrite Keeps redirecting back to xampp main page

I'm building a new version of a PHP website to have SEO linking URL
I'm really bad with REGEX and have very little understanding of how to work with .htaccess but I've been trying for two days to make a URL Rewrite rule, which I think is almost there but not quite yet.
In my .htaccess I have:
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d [NC]
RewriteCond %{REQUEST_FILENAME} !-f [NC]
RewriteRule ^(.*)$ .php?id=$1 [QSA,L]
It's not just rewriting the end of the URL, it's redirecting to xampp main page. Please I'm really confused because I have tried several. Don't know if it's my hosting server that's the problem.
https://localhost/new%20owolab/?id=home
here's my index page:
/** Absolute path . */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
// Version
define('VERSION', '1.0.6');
// Check Version
if (version_compare(phpversion(), '5.3.0', '<') == true) {
exit('Please Upgrade To The Latest Version Of PHP From Version 5.3 + Required To Access This Site');
}
if (!ini_get('date.timezone')) {
date_default_timezone_set('UTC');
}
// Windows IIS Compatibility
if (!isset($_SERVER['DOCUMENT_ROOT'])) {
if (isset($_SERVER['SCRIPT_FILENAME'])) {
$_SERVER['DOCUMENT_ROOT'] = str_replace('\\', '/', substr($_SERVER['SCRIPT_FILENAME'], 0, 0 - strlen($_SERVER['PHP_SELF'])));
}
}
if (!isset($_SERVER['DOCUMENT_ROOT'])) {
if (isset($_SERVER['PATH_TRANSLATED'])) {
$_SERVER['DOCUMENT_ROOT'] = str_replace('\\', '/', substr(str_replace('\\\\', '\\', $_SERVER['PATH_TRANSLATED']), 0, 0 - strlen($_SERVER['PHP_SELF'])));
}
}
if (!isset($_SERVER['REQUEST_URI'])) {
$_SERVER['REQUEST_URI'] = substr($_SERVER['PHP_SELF'], 1);
if (isset($_SERVER['QUERY_STRING'])) {
$_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
}
}
if (!isset($_SERVER['HTTP_HOST'])) {
$_SERVER['HTTP_HOST'] = getenv('HTTP_HOST');
}
// Check if SSL
if (isset($_SERVER['HTTPS']) && (($_SERVER['HTTPS'] == 'on') || ($_SERVER['HTTPS'] == '1'))) {
$_SERVER['HTTPS'] = true;
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
$_SERVER['HTTPS'] = true;
} else {
$_SERVER['HTTPS'] = false;
}
require_once "header.php";
if(isset($_GET['id'])){
$id = $_GET['id'];
$filename = "layout/" . $id . '.php';
if(file_exists($filename)){
include $filename;
}else{
include "system/error.php";
}
}else{
include "layout/home.php";
}
require_once "footer.php";
?>````
I think this will get you the result you need :
New URL
https://localhost/new-owolab/?id=home
OR
https://localhost/newowolab/?id=home
Old URL
https://localhost/new%20owolab/?id=home

Codeigniter htaccess not working in ubuntu 16.04

This application biuld in Codeigniter Version = 3.1.3. when build this application work it properly with this htaccess file but today when i run this application & face this type of error.
When run my codeigniter website, htaccess file can't rewrite my
index.php url. so, requested URL was not found error shown.
properly working url => localhost/Magpie/index.php/Front_master/aboutus.html
Error url => localhost/Magpie/index.php/Front_master/aboutus.html
Here is my htaccess code:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /Magpie/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
Controller file: Front_master.php
<?php
class Front_master extends CI_Controller {
public $result = array();
public function __construct() {
parent::__construct();
//load models
$this->result["getContact"] = $this->GetInformation->getContact();
$this->result["getLogo"] = $this->GetInformation->getLogo();
$this->result["getSlide"] = $this->GetInformation->getSlide();
$this->result["getServices"] = $this->GetInformation->getServices();
$this->result["getContent"] = $this->GetInformation->getContent();
$this->result["getPropertyListing"] = $this->GetInformation->getPropertyListing();
$this->result["getBestDeal"] = $this->GetInformation->getBestDeal();
$this->result["getTeam"] = $this->GetInformation->getTeam();
}
public function index() {
$data = array();
$data['title'] = 'Home Page';
$data['header'] = $this->load->view('frontview/header', $this->result, TRUE);
$data['slider'] = $this->load->view('frontview/slider', $this->result, TRUE);
$data['dashboard'] = $this->load->view('frontview/dashboard', $this->result, TRUE);
$data['footer'] = $this->load->view('frontview/footer', '', TRUE);
$this->load->view('frontview/master', $data);
}
public function aboutus() {
$data = array();
$data['title'] = 'About Us';
$data['header'] = $this->load->view('frontview/header', $this->result, TRUE);
$data['dashboard'] = $this->load->view('frontview/about_us', $this->result, TRUE);
$data['footer'] = $this->load->view('frontview/footer', $this->result, TRUE);
$this->load->view('frontview/master', $data);
}
}
enter image description here
Use this htaccess code
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /Magpie/
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php/$1 [L,QSA]
</IfModule>
Step 2 :
Remove index.php in codeigniter config
$config['index_page'] = '';
Step 3 :
Allow overriding htaccess in Apache Configuration (Command)
sudo nano /etc/apache2/apache2.conf
and edit the file & change to
AllowOverride All
for www folder
Step 4 :
Enabled apache mod rewrite (Command)
sudo a2enmod rewrite
Step 5 :
Restart Apache (Command)
sudo /etc/init.d/apache2 restart
and use this url:
localhost/Magpie/Front_master/aboutus
Sometimes this is will come from the database issue. The error will show "Expression #8 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'tappo_stage_db.Ratings.rating' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by".Therefore you should want to run this command.
SET GLOBAL sql_mode=(SELECT REPLACE(##sql_mode,'ONLY_FULL_GROUP_BY',''));

Redirects not working after adding dynamic to static code

We are using for our ecommerce website ECT templates, and installed a code from a programmer that changed the dynamic url to static. However, we have some backlinks that we would like to redirect to the proper page (or we would settle for sending them all to one "all products" page that we have set-up. The redirect we have currently returns a page that says "This product has been removed." Not good!
Here is the code that is on the htaccess file for the dynamic to static:
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule (.*)$ /handle_url.php [L]
Here is the code in the handle_url.php file:
<?php
ob_start();
session_start();
include "vsadmin/db_conn_open.php";
function sli_escape_string($estr){
if(version_compare(phpversion(),'4.3.0')=='-1') return(mysql_escape_string(trim($estr))); else return(mysql_real_escape_string(trim($estr)));
}
$url = $_SERVER['REQUEST_URI'];
$url = trim($url, "/");
$pos = strpos($url,'?');
if ($pos > 0){
$url = substr($url,0,$pos);
}
$pos = strpos($url,".");
if ($pos > 0){
$urlspec = substr($url, 0, $pos);
} else {
}
$store_url = $url;
$sSQL = "SELECT pID FROM products WHERE pURL='" . sli_escape_string($url) . "'";
$query = mysql_query($sSQL);
if ($query && mysql_num_rows($query)>0){
$rs = mysql_fetch_assoc($query);
$_GET['prod']=$rs['pID'];
$explicitid=$rs['pID'];
include "proddetail.php";
$plid = $explicitid;
} else {
$sSQL = "SELECT sectionID, rootSection FROM sections WHERE sectionURL='".sli_escape_string($url)."'";
$query = mysql_query($sSQL);
if ($query && mysql_num_rows($query)>0){
$rs = mysql_fetch_assoc($query);
$_GET['cat']=$rs['sectionID'];
$explicitid=$rs['sectionID'];
$secid = $explicitid;
if ($rs['rootSection']==1){
include "products.php";
} else {
include "categories.php";
}
} else {
include "content.php";
}
}
// For sections we want the .html
?>
And here is what I have unsuccessfully been trying to use to send the old dynamic link to the static page (there is no line break):
redirect 301 /proddetail.php?prod=cooling-hydration-backpack-system http://www.veskimo.com/cooling-hydration-backpack-system.html
I so appreciate any help you can give me. I admit I am a bit out of my depth with this.
Thanks so much,
Janell
Try adding the following to the .htaccess file in the root directory of your site.
RewriteEngine on
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /proddetail\.php\?prod=cooling-hydration-backpack-system [NC]
RewriteRule ^ http://www.veskimo.com/cooling-hydration-backpack-system.html [L,R=301]

mod_rewrite error

I'm using mod_rewrite in my new website.
.htaccess file
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?rwr=$1
index.php file
if (isset($_REQUEST['rwr'])) {
if (substr($_REQUEST['rwr'], -1) == "/") {
$modrewrite = substr($_REQUEST['rwr'], 0, -1);
} else {
$modrewrite = $_REQUEST['rwr'];
}
$modrewrite = explode("/", $modrewrite);
}
if (isset($modrewrite) && $modrewrite[0] != "") {
$category = $modrewrite[0];
} else {
$category = null;
}
if (isset($modrewrite[1])) {
$service = $modrewrite[1];
} else {
$service = null;
}
if (isset($modrewrite[2])) {
$identification = $modrewrite[2];
} else {
$identification = null;
}
With this the link www.domain.com/service/webdesign/works go to -
$category = "service";
$service = "webdesign";
$identification = "works";
This works but I want to optimize it:
.htaccess file
RewriteEngine on
RewriteRule ^(.*)/(.*)/(.*)$ index.php?category=$1&service=$2&identification=$3
index.php file
$category = $_GET['category'];
$service = $_GET['service'];
$identification = $_GET['identification'];
But it doesn't work. Why? Can anyone help me?
Your rule should work fine for URL in question. It could be your Apache configuration and/or similarly named files that causing it. Lets take your example URL /service/webdesign/works. It is possible that you have file named service.php then Apache may ignore that rewrite rule for some reason.
You can use this approach:
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
# Do not do anything for already existing files
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .+ - [L]
# the rewrite rule
RewriteRule ^([a-z0-9\-_]*)(/([a-z0-9\-_]+))?(/([a-z0-9\-_]+))?$ index.php?category=$1&service=$3&identification=$5 [NC,QSA,L]
This is a tested and working solution.

Part of url passed as variable in query string incorrectly includes their query string

I am in the process of moving a site to another server and I've ran into a problem.
The site uses .htaccess to redirect to index.php so the index.php can use $_SERVER['REQUEST_URI'] to load the whatever page is being called... However i cannot find where the old server has the .htaccess rules...so I am doing my own.
The .htacess rules I use are:
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /index.php/?$1 [L,QSA]
the URL is newsiteurl.com/racintv/video_view?channel_id=2
and by printing out the params on the index.php page I am getting
Array ( [page] => racintv/video_view?channel_id=2 )
It should load the video_view page and pass channel_id (which loads a video playlist). This is not the case as it thinks the page to load is actually /video_view?channel_id=2
On the old site, I print out the params on the index.php page it prints
Array ( [page] => racintv/video_view )
and passes the ?channel_id=2 correctly as the video loads correctly
What am I missing in my .httacess that would pass ?channel_id=2 correctly?
Here is the PHP code which parses the URI
$path_info = trim(substr($_SERVER['REQUEST_URI'],1)) ;
$var_array = explode('/',$path_info);
$num_vars = sizeof($var_array);
if ($num_vars==1 or !($var_array[1])) {// in the form of '/foo' or '/foo/'
if ($var_array[0] && ! strstr($var_array[0],'index')) {
$var_array[1] = 'index'; // use index as the default page
$num_vars = 2;
}
}
if ($num_vars >= 2) { // in the form of '/foo1/foo2[/foo3 ...]'
$tmp_array = explode('.',$var_array[1]);
$var_array[1] = $tmp_array[0];
$page = $var_array[0] .'/'.$var_array[1];
$vars['page'] = $page;
$q_str = '';
for ($i=2;$i<$num_vars;$i++) {
$key = $var_array[$i];
$value = $var_array[++$i];
if ($key && $value) {
$vars[$key] = $value;
$q_str .= "$key=$value&";
$$key=$value;
}
}
}
//end of search engine friendly url parsing
The page parameter is missing:
RewriteRule ^(.+)$ /index.php/?page=$1 [L,QSA]

Resources