More mod_rewrite questions.

Associate
Joined
27 Jun 2006
Posts
1,473
Morning all - another Sunday, another stupid question from me.

I have the URL: http://domain.com/w4sG7A which has a random 6 character string that I would like to get mod_rewrite to rewrite the URL to domain.com/script.php?w4sG7A but only if there is the 6 character string.

If there is no 6 character string, or if it is more than or less than 6 characters, just go to the index page as normal.

Now, as far as I can see I need to search for the 6 characters using:

/[a-zA-Z0-9]{6}/

but how do I get that to check after the / of the domain name?

I have my 'regex for complete numpties' book on the way so hopefully this will be one of the last questions on regex from me.

Not sure why, but I just cannot get my head round this thing!

Cheers
M.


//EDIT: Forgot to put what I tried:
Code:
RewriteEngine On
RewriteRule /[a-zA-Z0-9]{6}/$ http://domain.com/redir.php?i=$1 [R,L]
 
Last edited:
I didn't worry about the regular expression when i was messing around with my short url thingmebob... ;p

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /shorturl.php?url=$0 [L]
 
Cheers Daz.

It is for a short url thing, thought I would have a play but as always this regex trips me up!
Without trying your solution, wouldn't that redirect everything to shorturl.php though, so if someone typed in http://domain.com/index.php they would be redirected to the shorturl.php script?

Thats why I was trying to do the 6 character thing to make sure its only the shorturls that get redirected.

//EDIT - just tried it and it does redirect everything to the redirect script (although I get 404 if I type anything!)

Cheers
M
 
Last edited:
It should re-direct any request that isn't for a file or directory that already exists. (hence the "RewriteCond %{REQUEST_FILENAME} !-f" )
 
If the above didn't work try....

RewriteEngine on
RewriteRule ^[a-zA-Z0-9]{6}$ /script.php?$1 [L]
RewriteRule ^(.*)$ /

or maybe

RewriteEngine on
RewriteRule ^[a-zA-Z0-9]{6}$ /script.php?$1 [L]
RedirectPermanent ^(.*)$ http://domain.com/
 
Imy's example will work with one modification:

Code:
RewriteEngine On
RewriteRule ^[a-zA-Z0-9]{6}$ script.php?$0 [L]
RewriteRule ^(.*)$ /

I.e. you need to use the zeroth match rather than the first, since you're not capturing the code with a group.

You can then access the code from PHP using $_SERVER['QUERY_STRING'], though perhaps a better approach to use would be simply to rewrite to script.php?code=w4sG7A, for example, so that you have a GET variable you can access it through.
 
Last edited:
Cheers for all the replies guys - just another way of confusing me, so many different ways of doing the same thing!

Went with Dazs' reply in the end, as I seemed to understand it a little more than the others.

Many thanks again for wasting your Sunday morning replying to me :)
 
Back
Top Bottom