user1995997
user1995997

Reputation: 591

Use .htaccess to prevent root directory from public access

I don't know such thing is possible or not practically, but let's give it a try. In past (more than three years ago), I came to know about solution like this (don't know exactly how it is), in one MVC tutorial.

Directory structure

What I Want To Do Is

When user access http://www.mysite.com/a/b/c/, redirect all requests to /public/index.php page. i.e., all requests to website will go through /public/index.php page, except images/, js/ and css/ directories, which are in public/.

Also, http://www.mysite.com/includes/ will redirect to index.php page, and get includes/ as $query.

Index.php page

<?php

// get init file from webroot directory, which will load all required php files.
define ('ROOT', dirname(dirname(__FILE__)));
require_once (ROOT . 'init.php');


// get query from url (here, $query = "a/b/c/")
if(isset($_GET['q'])) {
    $query = $_GET['q'];
}

// insert images, css etc. resource
echo "<img src='http://www.mysite.com/images/foo.jpg' />";
echo "<script src='http://www.mysite.com/js/bar.js'></script>";

?>

This will be useful for them who are using web-hosting, which doesn't provide one step up directory access to webroot.

EDIT

OK, I found the site from where I got this concept. See two .htaccess files used in root directory and public directory. Link to MVC tutorial

Upvotes: 1

Views: 4294

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74038

I assume the .htaccess is in WebRoot.

To rewrite all requests, you just use RewriteRule. When you want to exclude some paths, you use one or more RewriteCond

RewriteEngine on
RewriteCond %{REQUEST_URI} !/images/
RewriteCond %{REQUEST_URI} !/css/
RewriteCond %{REQUEST_URI} !/js/
RewriteCond %{REQUEST_URI} !/public/index\.php
RewriteRule .* public/index.php?q=$0 [L,QSA]

RewriteRule ^images/.+ public/$0 [L]
RewriteRule ^js/.+ public/$0 [L]
RewriteRule ^css/.+ public/$0 [L]

The flag QSA appends any other existing query string as arguments to index.php. If you don't want to append any existing query string, just leave the QSA flag out.

If you want the rewrite to be visible to the client, you must add the R flag to the RewriteRule, i.e. [R,L,QSA] or [R,L].

Upvotes: 3

Sudip
Sudip

Reputation: 2051

You can use another tricks, where your page will not redirected to another page but you will restrict other user to see the directory index

Options -Indexes

Add this text in your .htaccess file, it will generate a 403 errror (forbidden)

Upvotes: 1

Related Questions