views:

31

answers:

2

I have a classifieds website. Each classified is linked like this originally:

   mydomain.com/ad.php?ad_id=Bmw_M3_M_tech_113620829

What RewriteRule should I use to make this link look like:

   mydomain.com/Bmw_M3_M_tech_113620829

Also, what do I need to add to my .htaccess file? This is what I have so far:

Options +FollowSymLinks
Options +Indexes
RewriteEngine On
RewriteBase /

And I have just enabled mod_rewrite which was disabled at first on my Ubuntu server by using:

 a2enmod rewrite

Anything else I need to know or do?

Thanks

+3  A: 

It looks like you need something like this:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/ad\.php
RewriteRule ^(.*)$ ad.php?ad_id=$1 [L]

This should rewrite a request to mydomain.com/Bmw_M3 into mydomain.com/ad.php?ad_id=Bmw_M3.

The RewriteCond excludes direct requests to ad.php from being rewritten. The RewriteRule would simply substitutes anything after mydomain.com/ in place of the $1. The [L] (last) flag stops the rewriting process so that it won't apply any more rewrites for a request that is rewritten by this rule.

Daniel Vassallo
Daniel, `do you think you could you explain the code in detail?
Camran
@Camran: Updated my answer. Let me know if you need any further clarifications :)
Daniel Vassallo
A: 

You need to add the rule itself. Requires regex =)

RewriteRule ([a-zA-Z0-9_]+) ad.php?ad_id=$1

Of course, this regex should be fine tuned based on the ad ID you're passing on - by telling what characters can be in that ad ID and similar. For example, if all ad IDs are ending with and underscore and 9 digits, something like this:

RewriteRule ([a-zA-Z0-9_]_[0-9]{9}) ad.php?ad_id=$1

Oh, also, after enabling mod_rewrite restart apache. Make sure that AllowOverride is not set to None, cause in that case, apache will ignore .htaccess files in directories.

robertbasic
Robert, I have apache2 On a Ubuntu server, and all AllowOverride directives are in the 000-default file... Should I change all of them to 'AllowOverride All'?
Camran
Yes, that way .htaccess files will be executed.
robertbasic
Oh, I made a mistake in the second regex. There's a $ sign missing after the closing bracket: ``RewriteRule ([a-zA-Z0-9_]_[0-9]{9})$ ad.php?ad_id=$1``
robertbasic