Page 1 of 1

[mod_rewrite] 302 Redirect old .php URLs to rewritten ones

Posted: Thu Oct 13, 2011 3:51 pm
by lorenzo-s
Hi everyone. I've got a funny problem with mod_rewrite.
Some time ago I used it to rewrite ugly .php links to nicer ones. Let's assume I only defined a simple index.html -> index.php rule.
Now I want to get rid of old URLs also when users directly type them, I want that when someone point its browser to /index.php, he will be visually redirected (302) to /index.html and display the page. So I tried something like:

Code: Select all

# Mod Rewrite init
RewriteEngine on
RewriteBase /

# First rule (it works alone)
RewriteRule ^index\.html$ index.php [L,QSA]

# Second rule for redirect old urls to new ones
RewriteRule ^index\.php$ index.html [R=302,L,QSA]
But obviously this creates an infinite redirect loop.
How can I achive the behaviour I want? :banghead: :banghead: :banghead:

Re: [mod_rewrite] 302 Redirect old .php URLs to rewritten on

Posted: Fri Oct 14, 2011 2:03 pm
by lorenzo-s
I found a solution that doesn't affect and doesn't use mod_rewrite.
I will check the $_SERVER['REQUEST_URI'] variable on the beginning of every PHP page, and if I found an old URL, I will redirect user using PHP.

Re: [mod_rewrite] 302 Redirect old .php URLs to rewritten on

Posted: Mon Oct 17, 2011 10:30 am
by pickle
I don't understand your problem. Do you want people to go to index.html or index.php?

Re: [mod_rewrite] 302 Redirect old .php URLs to rewritten on

Posted: Thu Oct 20, 2011 10:26 am
by lorenzo-s
Ok, let me explain.

Maybe the problem is that I used a too much simplified example. Let's say I have a rule like this:

Code: Select all

RewriteRule ^article/([0-9]+)/[0-9A-Za-z_\-]+\.html$ article.php?id=$1 [L,QSA]
So, I've prettified the "old" /article.php?id=345 to /article/345/the-article-title.html.
Now I want that when a user type /article.php?id=345, the browser redirects him to /article/345/the-article-title.html and then display the article page. I want he will never display a page using the old URL.

I couldn't do it using mod_rewrite again, because I've falled into redirection infinite loops...
So I solved putting at the beginning of the page some simple PHP lines that checks the $_SERVER['REQUEST_URI'] variable, and if it finds that the old URL has been typed, a redirect with header() is done to the new URL. It works perfectly.

Re: [mod_rewrite] 302 Redirect old .php URLs to rewritten on

Posted: Thu Oct 20, 2011 10:33 am
by pickle
Glad it's fixed. I think you may have been able to do it with just .htaccess by using a Redirect from article.php => article/..., then using the RewriteRule to show the PHP file again.

Re: [mod_rewrite] 302 Redirect old .php URLs to rewritten on

Posted: Thu Oct 20, 2011 2:09 pm
by lorenzo-s
I tried, but I got stucked in a redirection loop (experiencing the "This page is not redirecting properly" error by Firefox). Anyway... Lol at your signature. Bye!