htaccess - Blocking all but known file extenstions

Discussion in 'Apache' started by thing2b, Mar 27, 2008.

  1. #1
    I was wondering if someone could give me an example of how to block all but a few specific file extensions using htaccess?

    Anything except jpg, css and js need to be blocked.
     
    thing2b, Mar 27, 2008 IP
  2. Ladadadada

    Ladadadada Peon

    Messages:
    382
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    0
    #2
    RewriteCond %{REQUEST_URI) !\.jpg$ [NC]
    RewriteCond %{REQUEST_URI) !\.js$ [NC]
    RewriteCond %{REQUEST_URI) !\.css$ [NC]
    RewriteRule .* - [F,L]
    Code (markup):
    We have a very similar rule on our static content servers except that instead of blocking the non static files we redirect requests for anything dynamic back to the main dynamic webserver. For this, the last line should be:
    RewriteRule (.*) http://www.oursite.com/$1 [R=301,L]
    Code (markup):
     
    Ladadadada, Mar 27, 2008 IP
  3. thing2b

    thing2b Member

    Messages:
    45
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    48
    #3
    I am thinking that I should have been more explicit in my question. It code I use to block specific file extensions is:
    
    <FilesMatch "\.(html|php)$">
    	Order deny,allow
    	Deny from all
    </FilesMatch>
    
    Code (markup):
    I kind of want to alter this so it block all file extensions that are not specified.
     
    thing2b, Mar 27, 2008 IP
  4. Ladadadada

    Ladadadada Peon

    Messages:
    382
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    0
    #4
    I'm not all that familiar with FilesMatch so you may have to play around a bit but the changes I have made below should block anything that is not html or php.

    The first block denies everything and is then overridden by the second block. I'm not sure what order Apache processes these block in or which ones take precedence so you may have swap the order around or something like that.

    You could still replace all of that with the RewriteRules I mentioned above. I just used RewriteRules because that's what I am most familiar with.

    <FilesMatch ".*">
    	Order deny,allow
    	Deny from all
    </FilesMatch>
    
    <FilesMatch !"\.(html|php)$">
    	Order deny,allow
    	Allow from all
    </FilesMatch>
    Code (markup):
     
    Ladadadada, Mar 30, 2008 IP