简体   繁体   中英

How can I use a .htaccess rewrite to a page that has a php header redirect?

this is my first post so go easy on me.

Basically I am doing some rewrites in my htaccess file to change my made up search friendly URLs into actual URLs, and for the most part they are working. For instance this:

http://www.negativeworld.org/7849/news/nintendo-download-for-may-24-2012

Will turn into this:

http://www.negativeworld.org/article.php?id=7849

Just fine... IF that article exists. If the article doesn't exist, the php code uses this:

header("Location: boarderror.php");
exit;

To bring the user to boarderror.php. This works fine if it the user gets there directly on article.php and the id is bad, but when I am trying to do the htaccess redirect from a search friendly url and the id is bad, the htaccess redirect just hangs for awhile before giving me this message: "The page isn't redirecting properly".

What I want is for it to go to my boarderror.php page when there is a bad id. So basically I want my htaccess page to take a server friendly URL, switch to the true URL, and well... just let go at that point, and the PHP will take it from there. Here is my htaccess line that does the switch:

RewriteRule ^([0-9]+)/(news|review|editorial|podcast)/(.*)$ /article.php?id=$1 [L]

What am I doing wrong? (BTW I realize that if I set up all of my search friendly URLs correctly there should never be a bad id anyway, but I want to be on the safe side...)

Your thoughts aren't wrong. For a wrong ID there is a double redirection which is OK. The problem is how the second redirection happens. Try

header("Location: http://www.negativeworld.org/boarderror.php");

or

header("Location: /boarderror.php");

With your redirection the browser is trying http://www.negativeworld.org/9999/news/boarderror.php (being 9999 the wrong ID) which falls in an endless redirection loop that the browser cuts after 10 tries.

The redirect rule is fine, the issue is in your header function call. When you only provide a file name, the header redirect will send the user to the file in the same folder, much like creating an html link using only the filename.

Let's say i try to load http://www.negativeworld.org/99999/news/nintendo-download-for-may-24-2012 and that id is invalid. In this case it would send send the user to http://www.negativeworld.org/99999/news/boarderror.php which triggers the redirect again and gets stuck in an infinite loop (or would if the browser wasn't smart enough to stop requesting the same URL over and over again).

Per RFC 2616 the location header should provide an absolute URI, so you should do something like this:

header("Location: http://www.negativeworld.org/boarderror.php");
exit;

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