1

On my website, I have the following code to omit the extension of php pages

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]

I also added this code to show custom 404 pages

ErrorDocument 404 /404

Both of these work independently but not when used together. When I visit a dummy link like www.mydomain.com/pagethatdontexist, I want to see my 404 page, instead I see File not found error which is I guess coming from the server, so I'm getting a 404 on 404 apparently.

I've tried moving ErrorDocument above and below extension remover code, tried /404.php as well. I also tried creating an exception for 404 like

RewriteCond %{REQUEST_URI} !^/404.php$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Nothing works.

Edit: When extension code is removed and I visit www.mydomain.com/pagethatdontexist I see my 404 page. But if I visit www.mydomain.com/pagethatdontexist.php I see bland File not Found error from the server. Maybe it can give a clue as to what is going on.

Whip
  • 251
  • 1
  • 2
  • 8

2 Answers2

0

I think your regex doesn't match what you want. With the following i'm able to handle url like :

  • /mypage
  • /mypage/myid

The regex :

    RewriteEngine On # Activer le module Rewrite
    RewriteRule ^/(\w+)\/?$ /$1.php [NC,L]
    RewriteRule ^/(\w+)\/(\d+)$ /$1.php?id=$2
Martin
  • 446
  • 11
0

My guess is that you are on a LiteSpeed server, not Apache? This should "work" on Apache, but not LiteSpeed because of the way server variables are not updated between internal requests.

However, there is no need (and you should not) omit the file extension on the ErrorDocument directive itself. Extensionless URLs are "cosmetic" for users. The ErrorDocument is entirely hidden from users. But, if you omit the file extension on the ErrorDocument directive then it would trigger an additional internal rewrite, after the internal subrequest for the error document - which should be avoided.

So, you should include the file extension in the ErrorDocument directive:

ErrorDocument 404 /404.php
MrWhite
  • 11,643
  • 4
  • 25
  • 40
  • I am using Apache. It should and it does work on xampp but not on my server. Looks like `ErrorDocument` is ignored when extension remover code is present. Aren't these two completely separate directives? What could be interfering here? – Whip Oct 27 '21 at 09:20