r0skar
r0skar

Reputation: 8696

Custom 404 Rewrite + Exclude main dir from rewriting

I use .htaccess to display my 404 page, while showing the requested URL in the browser instead of the actual 404 URL. To do so, I have this line in my .htaccess:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /404.php [L]

This works good whenever I go to a non-existent file (i.e. blalba.php).

The problem is: When I try to go to my main site dir (i.e. http://example.com/), I see the 404 page. When I directly go to my index file (i.e. http://example.com/index.php), everything works just fine.


How could I modify the .htaccess to not redirect my main dir?

So that, in fact, the main dir is excluded from the rewrite code above.

ANSWER:

See answer below and adding RewriteCond %{REQUEST_FILENAME} !-d solved the problem!

Upvotes: 0

Views: 4361

Answers (2)

sven langebeck
sven langebeck

Reputation: 11

The following rule redirects to contact.html with subject= referencing the failed page

    ErrorDocument 404 /contact.php
    RewriteRule ^contact\.php$ /contact.html?subject=%{REQUEST_FILENAME} [L,R]

Upvotes: 1

Olivier Pons
Olivier Pons

Reputation: 15778

I'm pretty sure you just forgot to tell apache that it needs to "default" to index.php if nothing is precised in the url. Here's how you do:

<IfModule dir_module>
    DirectoryIndex index.html index.php
</IfModule>

Other answer about 404

I've had the same problem a few days ago. It's simple: assign the error document to 404.php. Whenever there's a 404, the server makes an internal redirection so that it can craft properly the web page.

So here's a sample of my vhost config:

<VirtualHost *>
    ServerName x.fr
    ...
    ErrorDocument 404 /404.php
    # activate rewrite engine:
    RewriteEngine On

    # *IMMEDIATELY* treat 404
    # if 404.php then stop immediately
    RewriteRule /404.php - [QSA,L]

    # From now on your can apply all your rules:
    ...
    ...
    ...
    # Sample of how I do a 404:
    RewriteCond %{ENV:PATH_LOCAL} notfound
    # "not found" 404 :
    RewriteRule .* - [R=404,L]
</VirtualHost>

With all that you should be able to create your own rewriterules with proper 404 "filtering".

Hope this helps!

Upvotes: 1

Related Questions