Question

Prevent CSS access with Apache

Posted January 8, 2022 115 views
Apache

I’m trying to deny access to my includes like CSS, Images and so on.

I think this can be achieved with Apache and .htaccess. So far I’ve wrote the following

RewriteRule ^includes/js/(.+) index [L,R]
RewriteRule ^includes/images/(.+) index [L,R]
RewriteRule ^includes/css/(.+) index [L,R]

The first rule works as expected but the following about images and css do not.

edited by KFSys

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
Submit an Answer
1 answer

Hi @teohristov,

I think the issue is that your first rule is preventing the next rules to work properly. I’ll suggest using Regex and make one rule rather than 3 or more depending on how much files you want to deny.

Try something like:

RewriteEngine ON
RewriteRule ^includes/(?:images|css|js) - [R=401,NC,L]

This should redirect all includes to a 401 page.

  • Thank you so much for the quick reply! Let me check that and get back to you as quick as possible.

    • Sure, it’s my pleasure!

      Don’t forget to clear your browser cache when checking if this works or not!

      • Yep, it’s working as expected! Thank you very much.

        I do have another question if that’s possible. I want to restrict access to different directories as well.

        When I applied the same rules in order to deny access to dir1 and dir2, only access to dir1 is being denied.

        The rule is

        RewriteRule ^includes/js/(?:dir1|dir2) - [R=401,NC,L]
        
        • Hi @teohristov,

          That’s a tricky one, here is what I think will work pretty good in your case:

          RewriteEngine On
          ##Rewrite rule for js with checking dir1 OR dir2 here...
          RewriteRule ^includes/js/(?:dir1|dir2) - [R=401,NC,L]
          ##Rewrite rule for JS or Images or CSS here ...
          RewriteRule ^includes/(?:images|css|js) - [R=401,NC,L]
          

          I hope this works for you. Let me know how it goes