如何使用 .htaccess 将直接请求重定向到父目录

How to redirect direct requests to parent directory with .htaccess

我正在使用 Symfony 并且我有一个 .htaccess 将根目录的连接重定向到 public 目录并重写 URL 以隐藏“/public/ " 部分,但现在我想阻止与 /public/ 目录的直接连接,我该怎么做呢?

我当前的 .htaccess:

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

我还在 public 目录中使用另一个 .htaccess,如下所示:

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}::[=11=] ^(/.+)/(.*)::$
    RewriteRule .* - [E=BASE:%1]

    RewriteCond %{HTTP:Authorization} .+
    RewriteRule ^ - [E=HTTP_AUTHORIZATION:%0]

    RewriteCond %{ENV:REDIRECT_STATUS} =""
    RewriteRule ^index\.php(?:/(.*)|$) %{ENV:BASE}/ [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',
           ]);
        }

现在导航至:localhost/new project/public

I want to block direct connections to the /public/ directory

因为您已经有了 /public/.htaccess,请在 .htaccess 的顶部添加此规则:

RewriteEngine On

RewriteCond %{THE_REQUEST} \s(?:/+(.+/))?public/ [NC]
RewriteRule ^ /%1 [L,R=301,NE]

# rest of your rules below this

THE_REQUEST 变量表示 Apache 从您的浏览器收到的原始请求,并且在执行其他重写指令后不会被覆盖。此变量的示例值为 GET /index.php?id=123 HTTP/1.1