5 .htaccess Snippets to Borrow from HTML5 Boilerplate

By  on  

HTML5 Boilerplate is an awesome website template when you want all best pieces in place for you when you start your project.  A while back I covered 7 CSS Snippets to Borrow from HTML5 Boilerplate, so today I want to feature a few .htaccess settings which could speed up, secure, and make your site very much more useful!

Block Access to Hidden Files and Directories

We try to push our code to productions servers without hidden files and directors, like our revision system directors, but that doesn't always happen.  This snippet prevents those files from being accessible:

<IfModule mod_rewrite.c>
    RewriteCond %{SCRIPT_FILENAME} -d [OR]
    RewriteCond %{SCRIPT_FILENAME} -f
    RewriteRule "(^|/)\." - [F]
</IfModule>

Hackers shouldn't have the ability to get those files so now they can't!

Compress Served Files by MIME Type

There are a number of file types we know we want compressed on the way out, and with mod_deflate, we can direct the server to do so:

<IfModule mod_deflate.c>

    # Compress all output labeled with one of the following MIME-types
    # (for Apache versions below 2.3.7, you don't need to enable `mod_filter`
    #  and can remove the `<IfModule mod_filter.c>` and `</IfModule>` lines
    #  as `AddOutputFilterByType` is still in the core directives).
    <IfModule mod_filter.c>
        AddOutputFilterByType DEFLATE application/atom+xml \
                                      application/javascript \
                                      application/json \
                                      application/rss+xml \
                                      application/vnd.ms-fontobject \
                                      application/x-font-ttf \
                                      application/x-web-app-manifest+json \
                                      application/xhtml+xml \
                                      application/xml \
                                      font/opentype \
                                      image/svg+xml \
                                      image/x-icon \
                                      text/css \
                                      text/html \
                                      text/plain \
                                      text/x-component \
                                      text/xml
    </IfModule>

</IfModule>

I love how easy it is to compress files by MIME type with .htaccess.  Tiny amount of code, massive enhancement for all of your users!

Allow Cross-Domain Fonts with CORS

I had no idea how big of a response I'd have when I first posted about cross-domain fonts.  They're a big, confusing problem for people but HTML5BP also has a solution:

<IfModule mod_headers.c>
    <FilesMatch "\.(eot|otf|ttc|ttf|woff)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>

Fonts are best served off of CDN so now you can do so without issue!

Allow Cross-Domain Images with CORS

Images are usually cool to serve from a different domain but if you want access to their data with canvas, you're in trouble.  This snippet allows you to get raw image data via canvas:

<IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
        <FilesMatch "\.(cur|gif|ico|jpe?g|png|svgz?|webp)$">
            SetEnvIf Origin ":" IS_CORS
            Header set Access-Control-Allow-Origin "*" env=IS_CORS
        </FilesMatch>
    </IfModule>
</IfModule>

After you get that image data, you can add filters and more.  Here's a tutorial showing you how to convert the image to canvas!

Expires

Expires headers are an awesome way of setting long cache expirations on your files.  Setting long expiration times on your static files (CSS, images, JavaScript, etc.) can be a massive performance boost!

<IfModule mod_expires.c>

    ExpiresActive on
    ExpiresDefault                                      "access plus 1 month"

  # CSS
    ExpiresByType text/css                              "access plus 1 year"

  # Data interchange
    ExpiresByType application/json                      "access plus 0 seconds"
    ExpiresByType application/xml                       "access plus 0 seconds"
    ExpiresByType text/xml                              "access plus 0 seconds"

  # Favicon (cannot be renamed!) and cursor images
    ExpiresByType image/x-icon                          "access plus 1 week"

  # HTML components (HTCs)
    ExpiresByType text/x-component                      "access plus 1 month"

  # HTML
    ExpiresByType text/html                             "access plus 0 seconds"

  # JavaScript
    ExpiresByType application/javascript                "access plus 1 year"

  # Manifest files
    ExpiresByType application/x-web-app-manifest+json   "access plus 0 seconds"
    ExpiresByType text/cache-manifest                   "access plus 0 seconds"

  # Media
    ExpiresByType audio/ogg                             "access plus 1 month"
    ExpiresByType image/gif                             "access plus 1 month"
    ExpiresByType image/jpeg                            "access plus 1 month"
    ExpiresByType image/png                             "access plus 1 month"
    ExpiresByType video/mp4                             "access plus 1 month"
    ExpiresByType video/ogg                             "access plus 1 month"
    ExpiresByType video/webm                            "access plus 1 month"

  # Web feeds
    ExpiresByType application/atom+xml                  "access plus 1 hour"
    ExpiresByType application/rss+xml                   "access plus 1 hour"

  # Web fonts
    ExpiresByType application/font-woff                 "access plus 1 month"
    ExpiresByType application/vnd.ms-fontobject         "access plus 1 month"
    ExpiresByType application/x-font-ttf                "access plus 1 month"
    ExpiresByType font/opentype                         "access plus 1 month"
    ExpiresByType image/svg+xml                         "access plus 1 month"

</IfModule>

You may be asking yourself about updating your files and issues with new file versions not being update.  Add a querystring to your file URL and the file version will be downloaded by clients at the appropriate time!

HTML5 Boilerplate is a goldmine of useful code.  Even if you don't want to included all of it within your project, take a few minutes to check out the CSS, htaccess, and JavaScript code it provides you -- it could teach you a technique to carry with you throughout your career!

Recent Features

  • By
    Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...

  • By
    Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

Incredible Demos

  • By
    MooTools Accordion: Mouseover Style

    Everyone loves the MooTools Accordion plugin but I get a lot of requests from readers asking me how to make each accordion item open when the user hovers over the item instead of making the user click. You have two options: hack the original plugin...

  • By
    Create a 3D Panorama Image with A-Frame

    In the five years I've been at Mozilla I've seen some awesome projects.  Some of them very popular, some of them very niche, but none of them has inspired me the way the MozVR team's work with WebVR and A-Frame project have. A-Frame is a community project...

Discussion

  1. sven

    Hi,

    one or two weeks ago i used some of this snippets too. But the compression didn’t work because i haven’t used the “Proper MIME types for all files”, it’s a section in the h5bp htaccess. After integrating that, it runs very well :)

  2. Doug

    You don’t “add a query string” to your CSS file. They have built in cache busting that is more robust than that even. Query strings are problematic in some cases.

  3. Great advice. I often neglect the importance of proper server configuration. Apart from the performance gain, the stuff that has been added under “Security” over the years is definitely worth checking.

  4. I want to make the htaccess file as i want to make the urls SEO Friendly …… pLease tell me the procedure of the same

  5. hi, that’s good
    how can I set expires when in html5 like this:

    it doesn’t include type=”text/css”.
    in this case, cache expire works?

  6. HTML5 Boilerplate look seems to work well on Linux server,Has IT ?, if I paste this code to your .htaccess Joomla open source then it will not work, I think I will try once. there is a difference between applying XHTML and HTML5 .htaccess ?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!