Tutorial :htaccess conditions + url rewrite


Currently, I have the setup in my htaccess so that example.com/dept/noc goes to: example.com/index.php?dept=dept&n=noc using

RewriteEngine On  RewriteRule ^([A-Za-z]+)/([A-Za-z]+)$ index.php?dept=$1&n=$2 [QSA]  RewriteCond %{SERVER_PORT} 80  

I have a folder called upload, how would I ensure that url rewriting is not in effect (an exception) for the /upload/ folder, since

example.com/upload/file.doc doesn't work?



RewriteEngine On  RewriteCond %{REQUEST_URI} !^/upload/.*  RewriteRule ^([A-Za-z]+)/([A-Za-z]+)$ index.php?dept=$1&n=$2 [QSA]  RewriteCond %{SERVER_PORT} 80  


A more general approach would be to add a condition to not rewrite if the URL directly matches an existing file or directory:

RewriteCond %{REQUEST_FILENAME} !-f  RewriteCond %{REQUEST_FILENAME} !-d  

This way you don't have to maintain a list of /upload, /images etc. folders in your rewrite rules. If file.doc doesn't exist in /upload, the rewriting will get done however.


You can compare the match of the particular groups like this:

RewriteCond $1 !=upload  RewriteRule ^([A-Za-z]+)/([A-Za-z]+)$ index.php?dept=$1&n=$2 [QSA]  

Note that != indicates a lexicographical comparison but you can use a regular expression as well:

RewriteCond $1 !^upload$  RewriteRule ^([A-Za-z]+)/([A-Za-z]+)$ index.php?dept=$1&n=$2 [QSA]  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »