Htaccess redirect everything except two files

.htaccess

Would anybody know how to write an .htaccess file that will redirect ALL traffic for ALL requests to index.php except for two files.

And in this process, also redirect any request without "www" to "www"

And also, can I make the .htaccess in the root directory the only main one to be used, followed, read, etc. So I don't have to put .htaccess files in every sub folder.

And also, should I put [NC] at the ends of these directives?

Tried:

DirectoryIndex index.php

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$
RewriteCond %{REQUEST_URI} ! ^/robots\.txt$
RewriteCond %{REQUEST_URI} ! ^/googlestuff\.html$
RewriteRule ^/?$ "http\:\/\/www\.example\.com\/" [R=301,L]

but it didn't work???

Best Answer

You're ! needs to be right before the regex otherwise apache mistakes it as its own parameter and assumes it's the pattern. Your pattern in the rule itself needs to be generic enough to match everything.

DirectoryIndex index.php

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/robots\.txt$
RewriteCond %{REQUEST_URI} !^/googlestuff\.html$
RewriteRule ^/?(.+) http://www.example.com/ [R=301,L]

If you want to force requests to have a www in the hostname, you have to do that separately, and this is where you'd want to use the NC flag:

RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]