2
votes

I had a custom 404 error redirect page working just fine through htaccess. However, after adding new code to htaccess, it stopped working. What's causing the conflict and how can I fix it?

EDIT: I've tried putting the ErrorDocument line at the top of the page and it still doesn't work.

htaccess code:

RewriteEngine On

#Removes www
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule . http://%1%{REQUEST_URI} [R=301,L]

#Redirects to extensionless php urls
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^&\ ]+).php
RewriteRule .* /%1? [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ $1.php [L]

#Redirect nonexistent files to a 404 page (not working)
ErrorDocument 404 /404.html
2
put the errorDocument statement at the top of the file. - Martin
I tried that actually, it still doesn't work. :-/ - jamiestroud69

2 Answers

2
votes

The problem is not about putting ErrorDocument in the top or in the bottom of your htaccess.

You have an infinite loop because of your rule (the one rewriting to php extension).
You need to check if it exists before rewriting it, otherwise you'll get a loop conflict between your rule and ErrorDocument.

You can replace your current code by this one

RewriteEngine On

#Remove www
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

#Hide php extension (only for existing files)
RewriteCond %{THE_REQUEST} \s/(.+)\.php(?:\s|\?) [NC]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ /%1? [R=301,L]

#Redirect to extensionless php urls (only if it exists)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ /$1.php [L]

#Redirect nonexistent files to a 404 page
ErrorDocument 404 /404.html
0
votes

put the errorDocument statement at the top of the file. Above the RewriteEngine Statement.

This is the solution, however I can't tell you why the above htaccess code causes that to fail.