seaofinformation
seaofinformation

Reputation: 809

Rewriting .php to .html and redirecting .php to a 404 in .htaccess

I have a lot going on here in my .htaccess, and there's one more redirect I'd like to add, and I'm not sure how to do it.

All .php files are seen as .html, and if an actual .html file exists of the same name, that should be accessible. Everything is also routed through my main controller script, mycontroller.php. That's all working perfectly.

The thing I'd like to add here is a 404 error if .php extension is attempted. Here's what I have so far.

<IfModule mod_rewrite.c>
  RewriteEngine on 
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)\.html$ $1.php [NC,L]
  RewriteRule ^$ /index.php [QSA,L]
  RewriteCond %{ENV:REDIRECT_STATUS} ^$
  RewriteRule ^(.+)\.php - [F,L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !^/favicon.ico
  RewriteRule ^(.*)$ mycontroller.php [L,QSA] 
</IfModule>

I tried adding what I gathered from this post, which worked, but it had the unfortunate side-effect of making my home page (without the /index.html written in the URL) to a 404. The author of the answer updated another line to prevent this from happening, but it doesn't seem compatible with my current script -- so my home page without the /index.html written in still goes to a 404 error.

It could be just that I don't have the order right, so any help would be appreciated. Many thanks in advance.

Upvotes: 2

Views: 970

Answers (1)

anubhava
anubhava

Reputation: 785256

You can use rules like this:

DirectoryIndex index.php
RewriteEngine on 

# block direct access to .php files
RewriteCond %{THE_REQUEST} \.php [NC]
RewriteRule \.php$ - [F,NC,L]

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

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/favicon\.ico
RewriteRule ^ mycontroller.php [L] 

Upvotes: 2

Related Questions