Welcome to WebmasterWorld Guest from

Forum Moderators: Ocean10000 & phranque

Message Too Old, No Replies

URL Rewrite with a Question Mark?

3:23 pm on Feb 11, 2010 (gmt 0)

Preferred Member

10+ Year Member

joined:Dec 30, 2002
posts: 437
votes: 0

I'm trying to figure out how to implement a Rewrite (ugly to nice URL) rewrite.

The hard part is I also want to intercept requests going to the old url (php with parameters) and 301 the request over to the new clean url.

It seems the "?" in the old URL matching is a problem. How can I get around this?

My current iteration is something like this:
RewriteRule test.html$ script.php?db=parameter
RewriteRule script.php?db=parameter$ test.html [R=301]

Assume I can't modify the .php file, and I need to implement this entirely in a .htaccess file.

I do understand the foundational security reason for this ? handling issue, but there's got to be some workaround option.

Thank you for any help.
6:26 pm on Feb 11, 2010 (gmt 0)

Senior Member

WebmasterWorld Senior Member jdmorgan is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Mar 31, 2002
votes: 0

Your code creates an 'infinite' redirect/rewrite loop.

The solution is to check the request for the URL-with-query-string to be sure it's coming direct from the client (e.g. browser or robot) and not being internally requested as a result of the immediately-preceding internal rewrite.

We've posted this code a hundred times, but here it is again in case you can't find it with a site search...

# Externally redirect only direct client requests for
# 'unfriendly' dynamic URL to 'search-friendly' URL
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /script\.php\?(([^&#\ ]*&)*)db=([^&#\ ]*)((&[^#\ ]*)*)(#[\ ]*)?\ HTTP/
RewriteRule /script\.php http://www.example.com/test.html? [R=301,L]
# Internally rewrite 'search-friendly' URL requests to internal script filepath
RewriteRule ^test\.html$ script.php?db=parameter [L]

It is unclear whether the 'db' query string parameter is to be used in some way in the new 'friendly' URL, but in case it is, I have captured its value in "%3" for re-use in the rewrite rule's substitution URL.

It is also unclear if additional query parameters may precede or follow "id=" or if fragment identifiers/named anchors may be used. The query parameters preceding 'db=' (if any) will be available in %1, the trailing query parameters (if any) will be available in %4, and the fragment identifier/named-anchor (if any) will be in %6 if needed. If these are not needed for re-use, the RewriteCond can be simplified somewhat, but allowances should still be made for their possible presence in the requested URL due to 'unfriendly forces.'