Acidon
Acidon

Reputation: 1334

500 Internal Server Error returned instead of: 404 - Not Found

I am getting 500 Internal Server Error instead of: 404 - Not Found whenever I type a non-existent page address for my site.

My best guess it has something to do with my .htaccess settings:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301] 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ $1 [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.php [L,QSA] 

ErrorDocument 404 /404.php

My .htaccess checks and redirects all the urls to https://www. form. It also takes care of hiding .php extensions from the all of the pages.

It took me a long time to come up with above code and now I am really afraid to change anything since I am not really good with .htaccess syntax.

Any help or suggestions would be appreciated!

Upvotes: 1

Views: 1674

Answers (2)

anubhava
anubhava

Reputation: 785531

  1. Your 2 redirect rules must be combined into one to avoid multiple 301 redirects (bad for SEO and efficiency)
  2. You must check for presence of .php file before adding .php in your URI.
  3. Avoid hardcoding host name in your rule.

Full .htaccess:

ErrorDocument 404 /404.php

RewriteEngine On

## add www and turn on https in same rule
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

# if not a directory and .php file is present then add .php extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

Upvotes: 1

Mohammed Elhag
Mohammed Elhag

Reputation: 4302

After these tow lines :

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

Add this line :

RewriteCond %{REQUEST_FILENAME}\.php -f

to make sure that request accept php extension before sending to it :

RewriteRule ^(.*)$ $1.php [L,QSA] 

When you send non-existing requests to any target make sure that target will manage this issue properly otherwise server will give error .

Upvotes: 0

Related Questions