Damian Sia
Damian Sia

Reputation: 489

Htaccess redirect a specific subdirectory

My current .htaccess file contains the following lines:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

I would like to redirect www.domain.com/category/automotive/used+car+dealers to www.domain.com/category.php?category=automotive&subcategory=used+car+dealers.

Should be dynamic and not a static redirect, as I will have other categories and subcategories? Can anyone show me some light on how to proceed from here?

I have googled, and browsed Stack Overflow for nearly 2 hours, but I'm still unable to come out with a solution.

[Sample 1]

RewriteEngine On
RewriteRule ^category/([\w-+]+)/([\w-+]+)$ category.php?category=$1&subcategory=$2 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

I have tweak abit and is able to redirect to the correct file, but somehow the page loads without css and images. please advise. thankyou.

[Sample 2]

RewriteEngine On
RewriteBase /websitefolder/

RewriteRule ^category/([\w-+]+)/([\w-+]+)$ category.php?category=$1&subcategory=$2 [R,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

This works fine just that the url will become category.php?category=automotive&subcategory=used+car+dealers instead of /category/automotive/used+car+dealers. but i wish to have the latter. please advise

Upvotes: 2

Views: 392

Answers (2)

ThinkingMonkey
ThinkingMonkey

Reputation: 12727

Try this:

RewriteEngine On
RewriteBase /

RewriteRule ^(category)/([\w-+]+)$ $1.php?$1=$2 [R,L]

RewriteRule ^(category)/([\w-+]+)/([\w-+]+)$ $1.php?$1=$2&subcategory=$3 [R,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

RewriteEngine On
RewriteBase /websitefolder/

RewriteRule ^category/([\w-+]+)/([\w-+]+)$ category.php?category=$1&subcategory=$2 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Just remove the R flag from :

RewriteRule ^category/([\w-+]+)/([\w-+]+)$ category.php?category=$1&subcategory=$2 [R,L]

It will not change the URL in the browser.

Upvotes: 1

Olivier Pons
Olivier Pons

Reputation: 15816

Here's what should fit your exactly your need:

RewriteEngine On
RewriteBase /
RewriteRule ^category/([a-zA-Z0-9]+)(/([a-zA-Z0-9]+))?$ category.php?category=$1&subcategory=$3 [QSA,NC,L]

Now if you want something more generic, i.e.:

www.domain.com/category/automotive/used+car+dealers
=>
www.domain.com/category.php?category=automotive&subcategory=used+car+dealers

and

www.domain.com/title/automotive/used+car+dealers
=>
www.domain.com/title.php?title=automotive&subcategory=used+car+dealers

Please see ThinkingMonkey's answer it's better than mine :).

Upvotes: 0

Related Questions