views:

184

answers:

3

Hello all,

Is it possible to re-write (Apache Mod-Rewrite) a URL from this:

http://www.example.com/view.php?t=h5k6 to this http://www.example.com/h5k6

The reason for this re-write is that the URL needs to be very short (a bit like a tiny URL service).

Would that new URL still hit my view.php page? Would it be able to still make use of the super global array GET ($_GET) to access the variable t? I still want my index.php page to map to this http://www.example.com.

I would also appreciate comments on effects this may have as I am a bit of a noob. :)

Thanks all

+12  A: 

The terminology of mod-rewrite works the other way. Requests would come in like this http://www.example.com/h5k6 and would be rewritten to http://www.example.com/view.php?t=h5k6 internally. That way your PHP scripts can respond to the requests as if they were sent as GET parameters, but users see the URLs in a much friendlier way.

So you don't have to change any PHP scripts, and you can still access the parameter t from the GET array.

In your case, the rule would look like this:

RewriteRule ^/(.*) /view.php?t=$1

You might want to be more specific about what you accept (instead of just the catch-all .* expression). Also, you might want exceptions to this rule if you have other pages in this directory other than view.php.

Welbog
+2  A: 

Try one of these:

# /view.php?t=h5k6 externally to /h5k6
RewriteCond %{THE_REQUEST} ^GET\ /view\.php
RewriteCond %{QUERY_STRING} ^([^&]*&)*t=([^&]+)&?.*$
RewriteRule ^/view\.php$ /%2 [L,R=301]

# /h5k6 internally to /view.php?t=h5k6
RewriteRule ^/([0-9a-z]+)$ view.php?t=$1 [L]
Gumbo
+1  A: 

Yes, this is definitely possible and will have exactly the effect you describe. However, your terminology is backwards. The "short" URL is the one the browser originall sends to the server, and it is rewritten to the longer version that is then actually processed and results in a PHP request.

Pretty much the only catch is that if used carelessly, this could result in search engines indexing both URLs and considering them duplicate content, which is bad for your ranking. On one hand, this can (and should) be avoided by never publishing the "long" version anywhere (i.e. all site-internal links have the "short" format). However, since you might publish them accidentally (which can happen easily), you should also use link rel="canonical" to tell search engines the URL you want your pages indexed under.

Michael Borgwardt