NedStarkOfWinterfell
NedStarkOfWinterfell

Reputation: 5203

MOD_Rewrite directive to implement a catchall redirection

In my website, there are three to four types of URLS (each can have different parameters to represent different pages). They are like http://foo.com/users/username, http://foo.com/questions/question_text, http://foo.com/new_question, etc.

I use mod_rewrite to rewrite the URL coming from client-side, i.e http://foo.com/users/username becomes http://foo.com/users?username=username, then this request goes to http://foo.com/users, which does the rest.

Now I want that, barring these 3-4 pre-defined templates, if any other request comes, like http://foo.com/abracadabra, the user should be redirected to the home page http://foo.com/. Is there any such directive that can implement this catchall redirection?

Upvotes: 1

Views: 68

Answers (1)

WWW
WWW

Reputation: 9860

A long way would be:

RewriteEngine On
# If the request isn't actually a file
RewriteCond %{REQUEST_FILENAME} !-f
# If the request isn't actually a directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request isn't specifically for favicon.ico (though the first 
# RewriteCond should take care of this, it's in the first .htaccess file
# I grabbed to verify)
RewriteCond %{REQUEST_URI} !=/favicon.ico
# Change the request from whatever the user entered to "/"
RewriteRule ^(.*)$ /

But you really shouldn't do this. It's much friendlier if you actually serve a 404 error and a custom error page if the requested page doesn't exist. Also, if you do this and your site has to go through a third-party security scan, you're going to generate a ton of false-positive security holes for the report.

Upvotes: 1

Related Questions