Htaccess – How to allow access only to static files for specific domain

.htaccessapache-2.2cdn

The idea is to serve js,css, img files using different domains so I created following domains:

  • css.mydomain.com
  • js.mydomain.com
  • img.mydomain.com

The main site URL is www.mydomain.com. When I access the site throw main URL every img,css,js files are delivered to user throw subodomains. And that everything works fine.

PROBLEM IS that I can access main site using one of domains css.mydomain.com, js.mydomain.com, img.mydomain.com

AND I want is to deny every request that is not js, css, img file type.

How can I do this over htaccess?

Best Answer

Thought I'd answer this since I ran into the same issue.

RewriteCond %{HTTP_HOST} ^css.mydomain.com$ [NC]
RewriteCond %{REQUEST_FILENAME} !\.(?:css)$ [NC]
RewriteRule ^ - [F]
RewriteCond %{HTTP_HOST} ^js.mydomain.com $ [NC]
RewriteCond %{REQUEST_FILENAME} !\.(?:js)$ [NC]
RewriteRule ^ - [F]
RewriteCond %{HTTP_HOST} ^img.mydomain.com$ [NC]
RewriteCond %{REQUEST_FILENAME} !\.(?:jpg|jpeg|png|gif)$ [NC]
RewriteRule ^ - [F]

So the first line checks the host against the matching string (case-insensitive).

Second line checks whether the requested file DOES NOT match an allowed extension (so you can change the allowed extensions by adding or removing - separated by a pipe). "?:" in regex is a non-capturing group match.

Third line sets the response to Forbidden should the request NOT match the allowed extensions in the second line.

Related Topic