Zach
Zach

Reputation: 442

htaccess causes 500 if page doesn't exist

I am currently using this code to remove the .php extension of my files on my apache web server.

Options -Multiviews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f    
RewriteCond %{REQUEST_FILENAME} !-d   
RewriteRule ^(.*)$ $1.php [L]

two questions:

1: when someone requests a page that doesn't exist, my web server is returning a 500 error instead of a 404. how can I fix this?

2: how can I force a 404 if someone requests the .php extension?

thank you in advance.

Upvotes: 1

Views: 160

Answers (3)

drew010
drew010

Reputation: 69937

The 500 error for non-existent pages is happening because mod_rewrite is going into an infinite loop trying to rewrite your request and terminates eventually.

Rewrite the rules like this to make sure the file with the PHP extension actually exists:

Options -Multiviews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f    
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [L]

The RewriteCond %{REQUEST_FILENAME}.php -f line will cause the rewrite to take place only if "file.php" exists.

Upvotes: 1

Kamil
Kamil

Reputation: 13931

This is not complete answer.

I try to explain how RewriteEngine works, if you don't understand that htaccess feature completely.

Apache server 'receives' some 'not real' url from your browser. Then it reads .htaccess, and by using information from that file it converts that 'not real' url to 'real' url pointing to physical file on server.

Error details are always saved to apache (httpd) error log. You have to read it, and if it not tells you anything - paste it here - we will help.

Forcing 404 error is bad idea in this case. You should fix error, not override it.

Upvotes: 0

Pritam Roy
Pritam Roy

Reputation: 1

example.com/about-us.php to go to example.com/about-us.html

RewriteEngine on
RewriteRule ^(.*)\.html$ $1.php

Upvotes: 0

Related Questions