acidpaul
acidpaul

Reputation: 165

Rewriting URL using .htaccess and mod_rewrite

I used this code in my .htaccess to rewrite my urls which is like this:

www.example.com/subcategory.php?subcat=my-test
to
www.example.com/my-test

.htaccess code I used:

RewriteEngine on
RewriteCond $1 !^(subcategory\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ subcategory.php?subcat=$1 [L,QSA]

My problem is whenever I access the url not pertaining to my subcategory.php file like contactus and aboutus, the .htaccess file will somehow put me to subcategory.php file which is not what I want. I want my contactus be handled by contactus.php and aboutus with aboutus.php.

I know that there is something wrong with my .htaccess file but I couldn't fix it by myself for I am not so familiar with the .htaccess coding.

Any suggestion would be greatly appreciated.

Thank you very much!

Upvotes: 0

Views: 241

Answers (1)

Ondřej Mirtes
Ondřej Mirtes

Reputation: 5626

You are rewriting all requests to subcategory.php. There is no way for .htaccess to tell whether /xxx is a subcategory or some different page, so you could redirect it to a different script.

RewriteEngine on 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L]

Use this code snippet instead of yours and move all the "routing" logic to PHP. In PHP, you can find out whether /xxx is a subcategory, a contact page, an article or something else and use a script suitable for that kind of database record.

You will find the requested URL in $_SERVER['REQUEST_URI'].

Upvotes: 2

Related Questions