Search code examples
php.htaccesscodeignitercodeigniter-3

Access codeigniter website homepage only at example.com and example.com/index.html and not at example.com/index.php


I need to access codeigniter website homepage only at example.com and example.com/index.html and not at example.com/index.php, I tried redirecting index.php to index.html with htacess but homepage becomes inaccessible. I do not want to show it is a php website. though I am able to display homepage at example.com/index.html by adding below in application/config/routes.php

$route['index.html'] = 'home/index';

But example.com/index.php is still accessible which I want to redirect to 404


Solution

  • Try adding the following at the top of your .htaccess file:

    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^index\.php$ / [R=302,L]
    

    This redirects any direct requests for /index.php to /.

    The condition that checks against the REDIRECT_STATUS environment variable ensures we only redirect direct requests and not rewritten requests by the Codeigniter front-controller (that appears later in the .htaccess file). Otherwise, you'll get a rewrite-loop (500 Internal Server Error response).

    The REDIRECT_STATUS env var is not set on the initial request from the client (ie. evaluates to an empty string, ^$). However, when the request to rewritten by the Codeigniter front-controller to index.php, REDIRECT_STATUS is set to the string 200 (representing a 200 OK HTTP status), so the above condition fails to match and the request is not redirected when Codeigniter rewrites the request to index.php.

    You could redirect to index.html as well using the above method, but index.html must be set up as a route in Codeigniter as you suggest.

    But example.com/index.php is still accessible which I want to redirect to 404

    If instead you want to serve a 404 (although a redirect, as above, would be preferable) then simply change the RewriteRule to read (keeping the condition as before):

    RewriteRule ^index\.php$ - [R=404]