views:

39

answers:

2

Hi,

I am setting up some rewrite rules on an Apache server using mod_rewrite. I was wondering if it was possible to write a rule that will basically re-direct the user to the home page if the page is not found i.e.

http://example.com/test  <-- does not exist

However, I would like if the user was to navigate to this domain they are automatically re-directed to:

http://example.com/

With this in mind, I don't want the URL to still display "http://example.com/test" I would like the URL to update itself to become "http://example.com/".

+3  A: 
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ http://domain.com/ [L,R=301]

Essentially, "if the requested filename is not a file or directory, redirect".

ceejayoz
That was superfast lol...I will give it a go thanks.
James
Worked like a charm thanks!
James
Slight problem...my other redirect rules are no longer working, everything is re-directing to the root! Any ideas? for example one rule is "RewriteRule ^enquiries(.*)$ index.php?m=feedback". Why is this no longer working?
James
Your other rules would need to come first, and have the [L] flag to prevent further rules from executing.
ceejayoz
Yeah I have them in front of the rule you provided, I added a backslash to them and it worked i.e. "http://domain.com/enquiries/" goes to the enquiries page, however, "http://domain.com.enquiries" redirects to the home page. Any ideas?
James
Just to update this, it was actually my rule for the enquiries page that was causing this issue I was using (.+) instead of (.*) like I had said I was using!
James
+2  A: 

I wouldn’t use a HTTP redirection but instead send an error document together with the proper error status code.

Gumbo
+1 I could re-direct the user to an error document and just display the correct error. I was looking for the correct rule tho as to how to re-direct the URL + update the URL
James