I'm using Symfony and I have a .htaccess that redirects connections to the root directory to the public directory and rewrites the URL to hide the "/public/" part but now I want to block direct connections to the /public/ directory how would I go about doing this?
My current .htaccess:
RewriteEngine on
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]
I am also using another .htaccess in the public directory which is as follows:
RewriteEngine On
RewriteCond %{THE_REQUEST} \s/+public/ [NC]
RewriteRule ^ - [F]
DirectoryIndex index.php
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI}::$0 ^(/.+)/(.*)::\2$
RewriteRule .* - [E=BASE:%1]
RewriteCond %{HTTP:Authorization} .+
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%0]
RewriteCond %{ENV:REDIRECT_STATUS} =""
RewriteRule ^index\.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ %{ENV:BASE}/index.php [L]
</IfModule>
<IfModule !mod_rewrite.c>
<IfModule mod_alias.c>
RedirectMatch 307 ^/$ /index.php/
</IfModule>
</IfModule>
Steps to reproduce:
- Install xampp (https://www.apachefriends.org/index.html)
- Install composer (https://getcomposer.org/)
- Open command prompt
- Enter the following commands
cd C:\xampp\htdocs
composer create-project symfony/website-skeleton "new project"
cd new_project
composer require apache-pack
php bin/console make:controller MainController
- Add the following code to MainController.cs located in src/Controller
#[Route('/main', name: 'main')]
public function index(): Response
{
$session = new Session();
$session->start();
// set and get session attributes
$session->set('name', 'Drak');
$session->get('name');
return $this->render('main/index.html.twig', [
'controller_name' => 'MainController',
]);
}
Now navigate to: localhost/new project/public
I want to block direct connections to the
/public/
directory
As you already have /public/.htaccess
, add this rule at top of that .htaccess
:
RewriteEngine On
RewriteCond %{THE_REQUEST} \s(?:/+(.+/))?public/ [NC]
RewriteRule ^ /%1 [L,R=301,NE]
# rest of your rules below this
THE_REQUEST
variable represents original request received by Apache from your browser and it doesn't get overwritten after execution of other rewrite directives. Example value of this variable is GET /index.php?id=123 HTTP/1.1