Forum Moderators: phranque

Message Too Old, No Replies

Mod rewrite problem

         

flurpalgames

7:18 pm on Aug 13, 2009 (gmt 0)

10+ Year Member



Hello!
I want to do this thing with the mod_rewrite module in the apache web server.

It involves editing the .htaccess file so that the apache server wll "rewrite" my urls.

What i have so far is this:
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^([0-9]+)$ gamepage.php?num=$1

...And what this does is when you go to /1 , the URL bar says /1, but it is actually showing the page gamepage.php?num=1
same with /2 and so forth...

But what i wish to happen is when you go to gamepage.php?num=1 (type it in and press enter), it changes the URL in the bar to /1, even though its still showing gamepage.php?num=1

Thanks!

jdMorgan

9:41 pm on Aug 13, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



So you need a rule that does the opposite function to your first rule, but only if the dynamic URL is requested by the client, and not as a result of your internal rewrite. It takes a RewriteCond to do this and avoid the 'infinite' redirect/rewrite loop that would otherwise result:

Options +FollowSymLinks
RewriteEngine on
#
# Externally redirect direct client requests (only) for dynamic URLs to corresponding static URLs
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /gamepage\.php\?num=([0-9]+)\ HTTP/
RewriteRule ^gamepage\.php$ http://www.example.com/%1? [R=301,L]
#
# Internally rewrite static URLs to gamepage script
RewriteRule ^([0-9]+)$ gamepage.php?num=$1 [L]

The contents of THE_REQUEST is the client request line, exactly as it appears in your raw server access log. Example:
GET /gamepage.php?num=3 HTTP/1.1

Jim

[edited by: jdMorgan at 11:16 pm (utc) on Aug. 14, 2009]

g1smd

9:53 pm on Aug 13, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



OK. So you have the 'rewrite' part working; but do add the [L] flag to the end of the rule.

Now you need to add a separate 'redirect' as well. Use another RewriteRule for that, this time using the [R=301,L] flags.

This topic comes up almost every day so there is a LOT of prior example code, as well as pointers from the forum charter.

jd replied while I was still typing. You got a good answer.

flurpalgames

7:46 pm on Aug 14, 2009 (gmt 0)

10+ Year Member



Thanks, this is great.

There is a problem, though.
Now, it is showing /1?num=1
How do I make it show only the /1

Thanks

g1smd

8:04 pm on Aug 14, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Add a question mark to the end of the target URL of the redirect.

That will clear the appended query string.

jdMorgan

11:17 pm on Aug 14, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Corrected above as noted. Thanks!

Jim

flurpalgames

4:56 am on Aug 15, 2009 (gmt 0)

10+ Year Member



Perfect! Thanks so much