Redirect user to public folder and restrict access to project root files

Asked

Viewed 204 times

-2

I am making use of a MVC structure with PHP and, for security purposes, my index.php file that loads the configuration files and gives the bootstrap in the project is inside the folder public/. Below is the project folder structure.

Estrutura de pastas do projeto

I need to make sure that when the user accesses the site (as I am in development environment, it would be: http://localhost/estrutura_mvc/), it is redirected to the file public/index.php and that this folder is the only one accessible to the user. I’m usually able to redirect to the index.php file using the following code in .htaccess:

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.*)$ ./public/index.php?route=/$1 [L,QSA]

However, this way the user has full access to files that are at the root of the project (for example: http://localhost/estrutura_mvc/.env returns the contents of this file without any kind of restriction). How do I make sure that the only files he has access to are the ones in the folder public/?

1 answer

2


I was able to find a solution. To solve, two files need to be created, one .htaccess at the root of the project, and a .htaccess inside the briefcase public (or the one you want to get the index).

To redirect to the folder public, the .htaccess at the root of the project should contain the following content:

RewriteEngine On
RewriteCond %{REQUEST_URI} !public/
RewriteRule (.*) public/$1 [L]

Already the .htaccess that’s inside the briefcase public shall contain the following content:

RewriteEngine On
RewriteBase /nome_da_pasta_do_seu_projeto
Options All -Indexes
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?route=/$1 [L,QSA]

Being the first two lines mandatory and the rest you can customize according to your application.

Credits go to Dhairya Lakhera who answered this question with the solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.