1

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/".

2 Answers 2

3
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".

Sign up to request clarification or add additional context in comments.

4 Comments

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?
Your other rules would need to come first, and have the [L] flag to prevent further rules from executing.
Yeah I have them in front of the rule you provided, I added a backslash to them and it worked i.e. "domain.com/enquiries" goes to the enquiries page, however, "domain.com.enquiries" redirects to the home page. Any ideas?
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!
2

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

1 Comment

+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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.