Is redirecting in htaccess providing enough security for sensitive pages?

This can provide adequate security, if configured correctly.

I can think of one common flaw: with Apache and rewrite rules, it is often possible to construct an URL that points to the same file and is not redirected. For example, requesting /Config/config.php redirects, but requesting //Config//config.php does not. This is because the rewrite rule matches an exact URL, not any variation.

Another common error when using redirecting for security is sending the header to redirect, but not preventing the page to render. An attacker can then access the pages by removing the Location header. However, this is typically an error in the application and not when using Apache to do the redirection.

A better way is to place the config file outside of the web root. So you have index.php in a subdirectory public, and config.php outside of this directory. This reduces the possibility that you expose the configuration.


The way your config.php is set up should not allow people to view the credentials even if they did have access to this file via the web browser.

Consider the following config file, borrowed from this example;

<?php
return (object) array(
    'host' => 'localhost',
    'username' => 'root',
    'pass' => 'password',
    'database' => 'db' );
?>

If a user were to navigate directly to this page, they would be greeted with a blank screen. This is because nothing in this script actually prints to the page. No information would be leaked.

I would suggest setting up your config in this sort of way - so that if for whatever reason your .htaccess fails it doesn't actually matter.


No.

Think about the following scenarios:

  1. Someone reconfigures your server and disables redirecing. Oops. Your .htaccess no longer protects you.
  2. Someone adds a redirection rule to the server configuration which preempts your redirection rule in the .htaccess file. No joy!
  3. Someone reconfigures your server and disables htaccess files. Again, no protection any more.
  4. Someone deletes the .htaccess file by mistake. Again, no protection any more.

Number 4 actually happened to me a few years back while I was migrating to a different server - I forgot to copy the .htaccess file. Thankfully, I noticed a few hours later and no harm was done. But Mistakes happen all the time. You should plan for them.

All these problems apply to any solution you implement using htaccess files. If you have access to your server's configuration, I'd place your directives there. I'd also protect your config endpoint with an additional layer of HTTP Basic Authentication (assuming you're using https to reach it, this adds considerable security).

If config.php is homegrown (rather than part of a third-party software package), I'd do the redirection the the login page inside the php script.