Search code examples
phplaravel.htaccess

exclude a directory from Laravel mechanism and access the directory directly


I have a website built on Laravel 9. Now for some reason, I need to add a folder/directory in the root (httpdocs) named "news".

When I go to my website e.g. mywebsite.com, Laravel website works fines as expected but when I go to mywebsite.com/news, the Laravel mechanism kicks in and shows an error page.

So my question is How can I make it (either through .htaccess or etc) so that Laravel does not get activated when I access the directory "news" and the contents inside "news"?

My .htaccess in root currently have this three lines

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

And .htaccess inside the public folder contains this -

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]   

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

I am on the Apache Plesk server. There are similar looking questions on StackOverflow but none mets my requirement


Solution

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

    You can add another condition (RewriteCond directive) to the root .htaccess file to prevent the request being rewritten to the (Laravel) /public subdirectory. However, your existing condition is incorrect and will always be successful (although strictly speaking this is not necessary anyway - which is why it still "works" - since the presence of the /public/.htaccess file effectively prevents the rewrite loop). It should read ^/public (with a slash), not !^public.

    For example:

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

    The first condition is successful only when the REQUEST_URI variable (root relative URL-path) does not (!) start with /news.

    The two conditions can be combined if you wish by changing the regex. ie. !^/(public|news).

    Alternatively, add the news directory in the public subdirectory (ie. /public/news) then you don't have to change either .htaccess file. (Although you should still "correct" the root .htaccess file as mentioned above.)