Home > Software engineering >  RewriteRule creating 500 Internal Server Error instead of 404
RewriteRule creating 500 Internal Server Error instead of 404

Time:10-31

My .htaccess working, it does what I want, but when I write a non-existing file to the address bar, it gives me 500 internal server error instead a 404 not found. Can you help me, why?

RewriteEngine ON
RewriteCond %{REQUEST_URI} !/?exception\.php [NC]
RewriteCond %{REQUEST_URI} !^/admin [NC]
RewriteCond %{THE_REQUEST} \s/([^.]*)\.php/?\s [NC]
RewriteRule ^ /%1? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/?$ $1.php [QSA,L]

RewriteCond %{THE_REQUEST} \s/new\.php\?article=(\S )\s [NC]
RewriteRule ^ /news/%1? [R=301,L]
RewriteRule ^news/([^/]*)$ new.php?article=$1 [NC,QSA,L]

RewriteCond %{THE_REQUEST} \s/category\.php\?catid=(\S )\s [NC]
RewriteRule ^ /news/categories/%1? [R=301,L]
RewriteRule ^news/categories/([^/]*)$ category.php?catid=$1 [NC,QSA,L]

CodePudding user response:

Your 2nd rule appears to be culprit that is writing to a .php for every URI that doesn't exist.

You can try this code in your site root .htaccess:

RewriteEngine On

RewriteCond %{THE_REQUEST} \s/category\.php\?catid=(\S )\s [NC]
RewriteRule ^ /news/categories/%1? [R=301,L]

RewriteCond %{THE_REQUEST} \s/new\.php\?article=(\S )\s [NC]
RewriteRule ^ /news/%1? [R=301,L]

RewriteCond %{REQUEST_URI} !/(exception\.php|admin) [NC]
RewriteCond %{THE_REQUEST} \s/([^.]*)\.php/?\s [NC]
RewriteRule ^ /%1? [R=301,L]

RewriteRule ^news/categories/([^/]*)$ category.php?catid=$1 [NC,QSA,L]

RewriteRule ^news/([^/]*)$ new.php?article=$1 [NC,QSA,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(. ?)/?$ $1.php [L]

Take note of last rule that adds .php extension only for URIs that have a matching .php file.

  • Related