32

I must do a little trick for a site! The idea is:

  • if a file for a required url exists then I go to that url, doing nothing more;
  • if a file for a required url not exists, I must go to a file.php and than do something, but NOT changing the url!

example:

www.mysite.com/page1.htm -> exists -> go to file page1.htm

www.mysite.com/page2.htm -> NOT exists -> go to file default.php but with url "www.mysite.com/page2.htm"

It's possible to do this all by .htaccess?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Kiavor
  • 476
  • 1
  • 7
  • 14
  • 1
    Also, give yourself a [meaningful username](http://tinyurl.com/so-hints). One advantage to this is others can use [at-replies](http://meta.stackexchange.com/questions/43019/how-do-comment-replies-work) to address you in their comments and you'll get a notification that someone has addressed you in a comment. – outis Jun 08 '11 at 04:59
  • Thx for suggestions. I'm not always in this site. I'll try to correct my mistakes :) – Kiavor Jun 23 '11 at 13:19

3 Answers3

81
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /default.php [L]
Wander Nauta
  • 18,832
  • 1
  • 45
  • 62
user237419
  • 8,829
  • 4
  • 31
  • 38
10

It is not mentioned here but FallbackResource is the new recommended way of handling not-found (404) URLs. Example:

FallbackResource /not-404.php 

From Apache manual:

Use this to set a handler for any URL that doesn't map to anything in your filesystem, and would otherwise return HTTP 404 (Not Found).

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Important to note, I have found that this can break some server side processed REST-style URLs, like: `http://example.com/app.php/some/resource`. – Resist Design Jul 25 '15 at 00:28
  • That's not correct. Behavior of `FallbackResource` will be same as `ErrorDocument`. If `PATH_INFO` is enabled then `/app.php/some/resource` works flawlessly and I've tested it on my Apache. – anubhava Jul 25 '15 at 07:29
5

Implement a 404 error rule. Doesn't require mod_rewrite:

ErrorDocument 404 /default.php
Vladimir
  • 159
  • 1
  • 2
  • This is also great if you want to use an HTML5 fallback without messing up rest style calls to php like `http://example.com/app.php/some/resource`. – Resist Design Jul 21 '15 at 05:55
  • I actually switched to this and it worked even better! – Resist Design Jul 21 '15 at 05:56
  • 2
    This might NOT be what you want. This will send a HTTP 404 status (file not found) header back to the browser (and to Google). So only use it for a useful 'file not found' page. – Andrew Murphy Feb 27 '17 at 09:53