Redirect or deny direct access to public folder

Asked

Viewed 425 times

2

I’m using htaccess to access the folders css, js, images who are in /public directly:

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteBase /
    RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [QSA,L]
</IfModule>

For example, when access is url http://localhost/css/file.css it shows the content of http://localhost/public/css/file.css

But I want to deny access if the user type the "public" in the address, for example http://localhost/public/css/file.css. It is possible to deny access if there is /public at the address?

2 answers

1

Whereas the Directive RewriteBase is the root of http://localhost/, add the following rule:

RewriteRule ^(public/) - [F,L,NC]

This rule will deny access to public/folder. If you want to add another specific path, see an example

RewriteRule ^(public/|outrapasta/) - [F,L,NC]

In this example, you are applying the rule to public/ and other/.

  • Thank you Daniel, I looked right now, actually the problem is different, when I try to access http://localhost/css/file.css error 403 appears too, which should only appear in http://localhost/public/css/file.css

1


To solve the problem you can use %{THE_REQUEST} with RewriteCond, examine:

RewriteCond "%{THE_REQUEST}" "^GET\s/public/"

If you need all methods (GET, POST, PUT, etc), example of redirect:

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteBase /

    RewriteCond "%{THE_REQUEST}" "^[A-Z]+\s/public/"
    RewriteRule ^public/(.*)$ other-directory/$0 [QSA,L]

    RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [QSA,L]
</IfModule>

Deny access (it will be necessary to create a false path):

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteBase /

    RewriteCond "%{THE_REQUEST}" "^[A-Z]+\s/public/"
    RewriteRule ^public/(.*)$ fake-directory/$0 [F]

    RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [QSA,L]
</IfModule>

Browser other questions tagged

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