简体   繁体   中英

Codeigniter: After cleaning my URLs(removing index.php) I couldn't redirect users who accessed my website to the new clean URL

I struggled(because of the hosting company, godaddy) to remove index.php? from my website's URLs, after accomplishing that.
after that I noticed some users are accessing my website using the old URL(the one with index.php?/ )
So, I tried to redirect the users coming from index.php? pages using 301 redirects, but no-luck.
I searched the internet a little bit,
but I think the reason behind the problem is that I need it to redirect from all URLs that
included index.php?/ to example.com or to the same page request but without index.php?/ (preferred).

for example: requesting example.com/index.php?/site/category/etc will lead to example.com or example.com/site/category/etc (preferred method).
And any other URL will be treated the same.

Here is my current .htaccess file (with nothing related to this issue) :

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]  

Update :
Trying php solution:(credits to Robin Castlin)
I tried using hooks(based on an answer), but did not work! i enabled hooks from config and URL helper is auto loaded.
this function is inside application/hooks/MY_hooks.php :

function redirectToNewURL(){

    if(preg_match('~/index.php?/~', $_SERVER['REQUEST_URI'])) {//check if the URL has index.php 
        header('Location: '.current_url(), true, 301); //redirect
        exit;
    }
}  

This how I set up the hook:
from application/config/hooks.php
I put this simple array:

$hook['pre_controller'] = array(
    'class' => '',
    'function' => 'redirectToNewURL',
    'filename' => 'MY_hooks.php',
    'filepath' => 'hooks'
);

Eventually, I got no result.

$CI =& get_instance();

$CI->load->helper('url');

if (preg_match("~/index\.php\?/~", $_SERVER['REQUEST_URI'])) {
    header('Location: '.current_url());
    exit;
}

Adding this to a hook or auto loaded helper should do it.

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