htaccess to rewrite uri into get if not file/folder

979 views Asked by At

I need htaccess rule that rewrites an uri into get variable if it is not for an existing file or folder. Example:

www.example.com/page1.php -> goto page1.php
www.example.com/page2.html -> goto page2.html
www.example.com/folder -> goto /folder
www.example.com/some_string_value -> rewrite as /default.php?value=some_string_value
1

There are 1 answers

4
Panama Jack On BEST ANSWER

That's really a very common request. There are probably 1000's of questions about this asked on this site. You need to use the RewriteCond and REQUEST_FILENAME to look for non existent folder and then internally rewrite to get variable. Essentially if it's a 404 (non existent URI) it will be routed to your default.php file. That's how pretty URL's are done. You can put this in your .htaccess file in the root.

RewriteEngine On
#prevent the use of the default.php file directly and redirect to friendly URI
RewriteCond %{THE_REQUEST} [A-Z]{3,9}\ /default\.php\?value=([^&\ ]+)
RewriteRule ^ /%1? [R=301,L]
#redirect non existent (404) folder to get variable
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ /default.php?value=$1 [L]