A Beginner’s Guide to .htaccess for Designers and Developers

Among the various tools for customizing your web server, the .htaccess config file is a tremendous asset. You can quickly reset document types, parsing engines, URL redirects, and many other crucial features.

Designers or developers who are not very technical may not get into the specifics of managing their own .htaccess file. But the topic itself is fascinating and worth some investigation.

For this article, I want to present some more purposeful concepts for designers and developers. Anybody who is launching their own website on an Apache server will want to understand how to manage their .htaccess file. It provides so much customizability and it can work across pretty much any web programming languages.

At the bottom of this post I have added some external web apps to help newcomers generate their .htaccess files dynamically.

Why use an .htaccess File?

This is a great question and perhaps we should start by answering “what is a .htaccess file“?

.htaccess is a very special configuration file used by the Apache web server. They can tell the web server how to present various forms of information and how to handle various HTTP request headers.

Really it is a means of decentralization to organize web server settings. One physical server may hold 50 different websites, each with its own .htaccess file. It grants a lot of power to webmasters, which would otherwise be impossible.

But why should you use one?

The biggest reason is security.

You can lock out certain directories or make them password protected. This is great for private projects or new CMS (Content Management Systems) where you want a little extra security. But there are also common tasks like redirecting 404 error messages to a certain webpage.

This only takes a single line of code, and it can dramatically impact how visitors react to missing pages.

Truthfully, there is not much I can say to convince others that a .htaccess file is worth understanding. Once you see it in action, then you can recognize all of the value which comes from this tiny config file.

Also, I hope the rest of this article may present some insightful topics to bring webmasters into the light of managing a .htaccess configuration.

Allow/Deny Access

It is possible to recognize potential spam visitors and deny them access to your website. This can be a little extreme. However, if you know that a person or group of people have been targeting your website, there are some options to choose from.

You could pick a domain referral to deny or ban visitors by IP address.

order allow,deny
deny from 255.0.0.0
deny from 123.45.6.
allow from all

Notice the 2nd IP address is missing the 4th integer. This code block will target the first IP(255.0.0.0) and every IP within the range of 123.45.6.0-255, then allow all other traffic.

Prevent Directory Listing

There will be times when you have an open directory that is set up to allow browsing by default. This means users can view all the files listed inside an internal directory structure, like your images folder.

Some developers do not want to allow directory listing, and thankfully, the code snippet is pretty easy to remember.

Options -Indexes

I have seen this answer presented countless times throughout Stack Overflow and it may be one of the easiest .htaccess rules to remember.

It is possible to actually create multiple .htaccess files inside each of these directories, so maybe one of them is password protected, but the others are not. And you can still keep the Options -Indexes so that visitors cannot browse through your website /images/ folder.

Password Protection

Password-protecting your directories is a very common procedure for securing administration areas and other folders crucial to your website. Sometimes you only want to offer access to a small group of people.

Other times, passwords prevent hackers from gaining access to your website administration panel. But either way, it is a very powerful solution to a whole number of problems.

To do so, we can add the rule below:

AuthType Basic
AuthName "This Area is Password Protected"
AuthUserFile /full/path/to/.htpasswd
Require valid-user

Notice that we need to provide a file named .htpasswd. This file should contain the username and the hashed password to allow access. Fortunately, you can simply use an external tool that allows you to generate it easily.

Security for WordPress

To put this password-protection idea to good use, let’s display a real-world example. This more complicated code snippet will force user authentication for anybody accessing the WordPress’ wp-login.php file.

You will find the original source on Ask Apache which has numerous other WordPress protection snippets.

<Files wp-login.php>
Order Deny,Allow
Deny from All
Satisfy Any
AuthName "Protected By AskApache"
AuthUserFile /web/askapache.com/.htpasswda1
AuthType Basic
Require valid-user
</Files>

And if you are going to follow these .htaccess rules, it might also help to password-protect the admin area. Typically the wp-login.php file is going to get the most hits from people attempting to brute force their way into your system.

So even just the sample codes above would be more than enough added security for your WordPress website.

HTTP/HTTPS URL Rewrite Rules

Rewriting URLs is probably one of the most common uses for .htaccess files. WordPress default installations can actually generate an .htaccess file right from the administration panel. This allows you to create pretty URLs which do not have the .php?p=1 structure.

I want to look at this rewrite example on how to update underscores to dashes since it contains a lot of the most important elements.

RewriteEngine and RewriteBase can almost always be set to these exact values. But you need the RewriteEngine turned on for anything else to work.

There are plenty of guides online explaining how to enable mod_rewrite and your hosting provider can also help.

Notice the syntax follows a pattern of RewriteRules at the top. These rules are used to match against cases that are being sent as an HTTPS request. These are answered by a RewriteRule which in this case redirects everything to the domain d.com.

The ending brackets like [R=301,L] are called rewrite flags which are important, but more of an advanced topic.

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
 
RewriteRule !.(html|php)$ - [S=4]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4-$5 [E=uscor:Yes]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4 [E=uscor:Yes]
RewriteRule ^([^_]*)_([^_]*)_(.*)$ $1-$2-$3 [E=uscor:Yes]
RewriteRule ^([^_]*)_(.*)$ $1-$2 [E=uscor:Yes]
 
RewriteCond %{ENV:uscor} ^Yes$
RewriteRule (.*) https://d.com/$1 [R=301,L]

If you want to delve a bit deeper you can find a long list of flags on this cheatsheet webpage.

The mod_rewrite syntax is definitely a little confusing but don’t be intimidated! The snippets can look a lot easier in other examples.

When just getting started, I have to recommend this mod_rewrite webapp that helps you generate code samples using real URLs.

This is a brilliant tool because you can look up various items in the syntax to see what they actually do in the Rewrite rules.

But don’t try to overload yourself on these all at once. It took me well over 3-4 months to really start understanding how to rewrite URLs with [0-9a-zA-Z]+ and similar patterns. Keep on practicing, and in time, I promise you will get this stuff like it’s common-sense knowledge.

Code Snippets for developers

I love easy-to-use snippets, and I want to put together this small collection of pertinent .htaccess codes for developers

Each of these ideas can fit nicely into your own .htaccess file along with other code blocks. Most of these snippets are great for solving quick problems or fixes in your web server environment.

Imagine the perfect Apache setup for brand new webmasters just getting started online.

Setting DirectoryIndex

You can tell Apache which documents should be initially treated as the “main” document with DirectoryIndex. Typically you’d want to target an index-named files such as index.html and index.php.

DirectoryIndex index.html index.php

The order of documents should start with the most important and move through the ranks to the least important. In the example above, if we do not have an HTML, then the fallback will go to index.php. And you could even name these files home.php or someotherfile.php and it is all valid syntax.

Force “www” or “non-www” subdomain

Google can work with both versions of your website domain if you do not specify www.domain.com or just domain.com. In my experience, it is best practice to choose one of these and set it as the only choice via .htaccess.

Then Google will not index various URLs, with some pointing to the WWW subdomain while others do not.

# Force WWW Subdomain
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain.com [NC]
RewriteRule ^(.*)$ https://www.domain.com/$1 [L,R=301]

# No Subdomain
RewriteEngine On
RewriteCond %{HTTP_HOST} !^domain.com$ [NC]
RewriteRule ^(.*)$ https://domain.com/$1 [L,R=301]

This code snippet comes from a CSS-Tricks archive and provides a very handy solution.

You should update the domain to be whatever you need for your own website. Otherwise, there will be problems, and you’ll notice right away! But I do highly support forcing one of these two options and it is at the top of my tasks list after launching a new website.

Force Media File Downloads

Another fairly important snippet allows forcing certain media types to download instead of being displayed in the browser.

Immediately, I can think of PDF documents and MP3 audio files which may be presented in a downloadable format, but here is how you can force them to download?

AddType application/octet-stream .zip .mp3 .mp4

Feel free to include even more file types at the end of this line. All of the media formats using the octet-stream MIME type will be downloadable. Forcing this through .htaccess is a very direct route to ensure people are not able to view these files in the browser.

Custom Error Documents

One last final piece I want to add is a full template of custom error documents. Usually these number codes are only seen on the server end. But there are plenty of these error documents which you should be familiar with.

A few examples might be 403/404 errors and the 301 redirect.

This error code template starts at 100 and moves upwards into 500 errors. Please note that you obviously do not need all of these. Only the most common errors would be necessary, and possibly a few obscure snippets if you feel the need.

If you do not recognize a code just look it up on Wikipedia to get a better understanding.

ErrorDocument 100 /100_CONTINUE
ErrorDocument 101 /101_SWITCHING_PROTOCOLS
ErrorDocument 102 /102_PROCESSING
ErrorDocument 200 /200_OK
ErrorDocument 201 /201_CREATED
ErrorDocument 202 /202_ACCEPTED
ErrorDocument 203 /203_NON_AUTHORITATIVE
ErrorDocument 204 /204_NO_CONTENT
ErrorDocument 205 /205_RESET_CONTENT
ErrorDocument 206 /206_PARTIAL_CONTENT
ErrorDocument 207 /207_MULTI_STATUS
ErrorDocument 300 /300_MULTIPLE_CHOICES
ErrorDocument 301 /301_MOVED_PERMANENTLY
ErrorDocument 302 /302_MOVED_TEMPORARILY
ErrorDocument 303 /303_SEE_OTHER
ErrorDocument 304 /304_NOT_MODIFIED
ErrorDocument 305 /305_USE_PROXY
ErrorDocument 307 /307_TEMPORARY_REDIRECT
ErrorDocument 400 /400_BAD_REQUEST
ErrorDocument 401 /401_UNAUTHORIZED
ErrorDocument 402 /402_PAYMENT_REQUIRED
ErrorDocument 403 /403_FORBIDDEN
ErrorDocument 404 /404_NOT_FOUND
 
ErrorDocument 405 /405_METHOD_NOT_ALLOWED
ErrorDocument 406 /406_NOT_ACCEPTABLE
ErrorDocument 407 /407_PROXY_AUTHENTICATION_REQUIRED
ErrorDocument 408 /408_REQUEST_TIME_OUT
ErrorDocument 409 /409_CONFLICT
ErrorDocument 410 /410_GONE
ErrorDocument 411 /411_LENGTH_REQUIRED
ErrorDocument 412 /412_PRECONDITION_FAILED
ErrorDocument 413 /413_REQUEST_ENTITY_TOO_LARGE
ErrorDocument 414 /414_REQUEST_URI_TOO_LARGE
ErrorDocument 415 /415_UNSUPPORTED_MEDIA_TYPE
ErrorDocument 416 /416_RANGE_NOT_SATISFIABLE
ErrorDocument 417 /417_EXPECTATION_FAILED
ErrorDocument 422 /422_UNPROCESSABLE_ENTITY
ErrorDocument 423 /423_LOCKED
ErrorDocument 424 /424_FAILED_DEPENDENCY
ErrorDocument 426 /426_UPGRADE_REQUIRED
ErrorDocument 500 /500_INTERNAL_SERVER_ERROR
ErrorDocument 501 /501_NOT_IMPLEMENTED
ErrorDocument 502 /502_BAD_GATEWAY
ErrorDocument 503 /503_SERVICE_UNAVAILABLE
ErrorDocument 504 /504_GATEWAY_TIME_OUT
ErrorDocument 505 /505_VERSION_NOT_SUPPORTED
ErrorDocument 506 /506_VARIANT_ALSO_VARIES
ErrorDocument 507 /507_INSUFFICIENT_STORAGE
ErrorDocument 510 /510_NOT_EXTENDED
Online .htaccess Webapps
Other Useful Resources

Final Thoughts

There are so many countless resources online discussing .htaccess files. My linked articles and webapps are a great place to get started. But keep practicing new ideas and don’t be afraid of testing out code snippets. As long as you have a backup file then you can test out anything you like and it is a fun learning experience.

If you have other ideas or suggestions about .htaccess management please share with us in the post discussion area below.

The post A Beginner’s Guide to .htaccess for Designers and Developers appeared first on Hongkiat.

30 Cool CSS Animations For Your Inspiration

CSS is one of the most versatile programming languages in popular use. From layouts and text effects to colour and size of your content, the possibilities are endless. One of the most interesting uses of CSS is to create animations. And this is what this post is all about.

This post lists some of the most creative CSS animations you’ll find on the web. From transition effects to character animations, you’ll find some really cool examples here that you can either directly use in your project or take inspiration from. So, take a look and pick your favorite.

10 CSS3 Animation Tools You Should Bookmark

.no-js #ref-block-post-25432 .ref-block__thumbnail { background-image: url(“https://assets.hongkiat.com/uploads/thumbs/250×160/css3-animation-tools.jpg”); }

10 CSS3 Animation Tools You Should Bookmark

As people tend to more easily perceive things that move, smartly used animations can enhance the user experience… Read more

CSS Loading Animation

Creator: patrikhjelm

Seven animated dots shift left and right to signify a loading action.

Animated Shopping Cart Icon

Creator: jonitrythall

Cute animated effects for when groceries are added to the shopping cart. Scroll down for more.

Hamburger CSS3 only animation

Creator: Dawid Krajewski

Built with pure CSS, no JS or anything else.

404 animated Character

Creator: With An Es

At least with this error page, a developer is working on it. Even if it is a 404.

CSS Mars Landing

Creator: mgitch

We have landed on Mars! Made with CSS.

The Avenger

Creator: mariosmaselli

Can you hear hulk’s anger shake through the screen? Cool, right?

Day / Night toggle

Creator: jsndks

Now, you can toggle day and night with CSS. Genius idea!

Google Now 3rd party app

Creator: codecalm

Google Now third party apps, animated.

Clo clo

Creator: judag

Does a rooster move like that? You bet it does, complete with the jiggy neck. Great CSS3 practice.

Another CSS Preloader

Creator: Maseone

An awesome CSS rhythmic loading animation. Hypnotic, isn’t it?

Submit button

Creator: auginator

Click to submit, and the button animates the loading process until submission is complete!

Elastic SVG Sidebar Material Design

Creator: suez

Drag the white bar to the right to see an elastic sidebar effect.

Particle button

Creator: igcorreia

Do what the button says: hover for awesomeness.

Gooey button

Creator: Lucas Bebber

Click for the Gooey effect. You’ll get it once you see it, and you will click on it a few times more. Amirite?

Flipside button

Creator: hakimel

Click on any side of the Delete button and the button will flip according to where you click.

True hamburger menu!

Creator: CharlesSmart

A truly delicious hamburger menu. Click the hamburger for effects

Cruisin’

Creator: yy

See motorbike go.

3D cube wave

Creator: waddington

Holy 3D Cube-sicles!

Signature animation

Creator: drygiel

Here’s a signature that is not actually a GIF animation, but instead a PNG sequence animated with CSS3.

Background gradient animation

Creator: quasimondo

This trick changes the background gradient from one color to the other in a smooth, continuous form.

Star wars toggle icon

Creator: rss

A hamburger menu gets transformed into lightsabers in battle (a cross).

GIF Style animation

Creator: jascha

Watch as a photo materializes from the midst of pixel art.

Focus in/out input animation

Creator: fluxus

A little animated pen animated writes atop the forom you are filling in.

Chromatic triangle

Creator: felipedefarias

An awesome optical illusion, yes, done with CSS3.

Coffee maker

Creator: thisisroger

Here’s a reminder to take your daily dose of coffee. Like you need one.

Chrome Dinosaur

Creator: nickspiel

Can’t reach the page you want beacuse of a dropped connection? Here’s the dinosaur you always see when that happens, only this time it is running from a meteorite!

CSS shake

Creator: elrumordelaluz

Hover over each effect to watch the little guy shake.

Newton’s Cradle Loader

Creator: All Things Smitty

If you know physics, you certainly know Newton’s cradle, but probably not like this.

Launch the Modal

Creator: koolhaus

Click to see the nice and smooth modal window animation.

Walking Robot

Creator: P233

This robot just keeps walking, and walking, and walking, around the Y axis.

Flexing Pagination Arrows

Creator: Hakim

From the first page to the last, this pagination animation shows clearly how if you are faring, pagewise.

Here’s more:

Animated 3D Helix

First one in the list is an incredible animation made by Marcofolio.net, using CSS3 3D transforms. The animation looks like magic itself, but you can actually learn to create a similar effect with the tutorial in the article!

animated 3d helix
Animated Buttons

A must-see for web designers, as the demo not only shows the possibilities of CSS3 animation but also provides very cool and practical button effects for inspiration!

animated buttons
Animation Menus

Trying to spice up your animation menus to make them look really cool and creative? This demo is for you.

animation menus
Big Deal

It’s the smooth and nice animation that made this demo a big deal.

big deal
CSS3 Man

Look out, here comes the CSS3 man! A perfect example to showcase the true potential of CSS3 animation.

css3 man
Dribbble Ball Bouncing

With the little use of graphic tricks comes to a nice and amusing CSS3 animation.

dribbble ball bouncing
Frame by Frame Animation

Frame by frame animation with CSS3? No problem!

frame by frame animation
Graph Animation

A simple but powerful animation for you to show/explain the graph in your site, learn to make it!

graph animation
Hover Effects

The future of the hover effect comes with CSS3. Sleek and promising.

hover effects
Infinite Zoom

Smooth animation; it’s also a nice way to show off your portfolio. The total zoom for the 26 images is 67108864:1.

infinite zoom
Kinect and CSS3

“14 body joints are tracked and converted into a short CSS animation using Xbox Kinect. The body data is brought into the browser where it is parsed and converted into CSS animations with animatable.com.”

kinect and css3
Matrix

Want to be as cool as Matrix? With the CSS3, you’re able to make it.

matrix
Morphing Cubes

Experimental demo exploring the CSS3 using 3D transforms, animations and transitions. The interesting part here is you can still select the text on the elements, even when they are still rotating.

morphing cubes
Our Solar System

You don’t need expensive standalone software to help students explore solar systems anymore.

our solar system
Duff Roll

“Mmmmmm….Homer would love the never-ending supply of beer.”

duff roll
Poster Circle

A simple yet interesting example showing you how to use CSS transformation and animation to achieve an interesting effect.

poster circle
Star Wars Crawl

Star Wars opening’s crawl effect! Just as epic as CSS3.

star wars crawl
Typography Effects

Besides button, menu, and hover effects, you can also achieve creative typography effects with CSS3. jQuery is also involved in this demo to style the letters of the words.

typography effects
Walking With Andrew Hoyer

Best of all, you can also learn to walk with Andrew Hoyer in the article!

walking with andrew hoyer
Wonder Webkit

A wonderful use of CSS3 3D transformations with JavaScript Matrix library. Sounds technical, but the outcome is rockingly cool.

wonder webkit
Zoetrope

What else you can’t do with CSS3 when Zoetrope is possible with it?

zoetrope

More:

Here are more related articles you might be interested in:

The post 30 Cool CSS Animations For Your Inspiration appeared first on Hongkiat.