Just about every content management system, most using WordPress, Drupal, and Joomla to host their website, you can think that’s hosted in a Apache, Linux or Unix environment makes use of mod-write and .htaccess.

Today, I’m going to give a quick and short explanation that seems to plague some when migrating from one web platform to a different web platform.

Have you ever attempted to visit a website and forget to put a trailing slash on the end of the url, yet you end up arriving at the desired page?

Or have you had the reverse and had the trailing slash removed from a url when adding it to a url?

Well, little did you know or realize, .htaccess is likely the responsible party involved for making such actions happen.

And here’s how you make it happen.

First, turn on the mod_write engine.

If you would like to remove the trailing slash, then add the following rule:

Or, If you would like to add the trailing slash, then add the following condition and rule:

We basically test the condition to see if pathname exists and if its a regular file. Not so fast there.

Let’s take a minute to understand the RewriteCond and what it consists of.

The first part of the RewriteCond is called a server variable, and the last part of the RewriteCond, the -f, portion is called an exception or special case.

Because the exclamation is used, the test is actually checking to see that the pathname DOES NOT exist and then applies the rule to add the slash in the RewriteRule following the RewriteCond.

Notice the R=301 for a permanent redirect at the end.  The L and R reference are commonly known as flags.

If you wanted a temporary redirect, then simply change 301 to 302, or simply put R as it by itself is a default temporary redirect.

And that’s it! That’s how you remove or add the trailing slash to a URL using .htaccess file.