WP-Mix

A fresh mix of code snippets and tutorials

Force Trailing Slash with .htaccess

This quick code snippet enables you to enforce that all directory URLs append a trailing slash. It is a very simple code snippet, only a few lines and done. Here are a few examples to give you a better idea of how it works.

Examples

Here are some examples to show how the code works. Let’s say that your site receives the following requests:

https://example.com/hello
https://example.com/visit/then/goodbye
https://example.com/whatever/directory/subdirectory

With the below code added to your site, the server will redirect such requests to the following URLs:

https://example.com/hello/
https://example.com/visit/then/goodbye/
https://example.com/whatever/directory/subdirectory/

Notice the difference: each URL now has a trailing slash appended. Note this only works for directory requests. If a file is requested, no trailing slash is added.

Code

To ensure that all directory requests include a trailing slash, add the following slice of .htaccess to your site’s .htaccess file:

# Force trailing slash
<IfModule mod_rewrite.c>
	RewriteCond %{REQUEST_URI} /+[^\.]+$ 
	RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
</IfModule>

Once in place, this .htaccess rule checks the request. If the request is for a directory and no trailing slash is specified, then one is added. So whether or not the request includes a trailing slash, one always will be added. No modifications to the code are necessary, strictly plug and play.

Learn more

.htaccess made easy