.htaccess url rewriting is working but not the redirection

112 views Asked by At

I'm working on a local server on an html/php application and I'm trying to use the Apache url rewrite module without success

The application was stored in ./Compta/index.php. I have to an .htaccess file in ./Compta/.htaccess

I would like to only use a rewritten url like :http://localhost/Compta/Test/

instead of : http://localhost/Compta/index.php?page=test

and redirect users if they try to go to the old url

The .htaccess file contains :

Options +FollowSymlinks

RewriteEngine on

RewriteRule ^([[:alnum:]]*)/$   /Compta/index.php?page=$1 [L]

RewriteRule ^([[:alnum:]]*)$   /Compta/index.php?page=$1 [L]

RewriteCond %{REQUEST_URI}  ^/index\.php$
RewriteCond %{QUERY_STRING} ^page=([[:alnum:]]*)$
RewriteRule ^(.*)$ http://localhost/Compta/%1/ [L,R=301]

When I go to http://localhost/Compta/Test/ the following line is working and my code includes in a div the content of test.php :

RewriteRule ^([[:alnum:]]*)/$   /Compta/index.php?page=$1 [L]

When I go to http://localhost/Compta/Test the following line is working but in firefox the url is rewritten to http://localhost/Compta/index.php?page=Test and this is not happening with http://localhost/Compta/Test2; the url isn't rewritten.

RewriteRule ^([[:alnum:]]*)$   /Compta/index.php?page=$1 [L]

To fix this and to redirect the old url I added these lines :

RewriteCond %{REQUEST_URI}  ^/index\.php$
RewriteCond %{QUERY_STRING} ^page=([[:alnum:]]*)$
RewriteRule ^(.*)$ http://localhost/Compta/%1/ [L,R=301]

But this is not working and when I go to http://localhost/Compta/index.php?page=Test the url isn't rewritten to http://localhost/Compta/Test/

Thank you in advance

1

There are 1 answers

0
Keke Dix On BEST ANSWER

I didn't find a solution with .htaccess but i found one with php so i added the following lines in top of my php files :

        if(preg_match("/\/Compta\/index\.php\?page=([[:alnum:]]*)/",@$_SERVER['REQUEST_URI'],$page)&&!empty($page[1]))
        {
            $new_url = "/Compta/";
            switch (strtolower($page[1])) {
                case "test":
                    $new_url = $new_url."Test/";
                    break;
                case "test2":
                    $new_url = $new_url."Test2/";
                    break;
                default:break;
            }
            header("Status: 301 Moved Permanently", false, 301); 
            header("Location: ".$new_url);
            exit;
        }

I test if the url begin with "/Compta/index.php?page=" AND if there is a parameter for "page" Then I initialise the variable which contain the new url Switch the content of my parameter I modify the new url and then I make the redirection to my new url :)