3.8
(99)

Last Updated on February 22, 2022 by Amit

Add trailing slash to URLs

This article is for Apache users who want to learn how to add a trailing slash to URLs.

A trailing slash is / character that appears at the end of URLs something like the following :
https://example.com/foo/bar/ .
In this article we will learn how to add a trailing slash to URLs using RewriteRule directive in an htaccess file.

How to add a trailing slash to URLs

One of the easiest and most convenient way to add or enforce trailing slashes on URLs is by RewriteRule directive.

You can write a single rule in your htaccess file that will apply to all URLs without a trailing slash.
You can use a 301 redirect rule in htaccess that can do the following :

Redirect 301
https://example.com/foobar
To
https://example.com/foobar/
Here is the Rule you can use to enforce a trailing slash :

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^(.+)$ /$1/ [L,R=301]

The rule doesn’t add a trailing slash to your existent files because you will not want to have your file URLs look something like /file.php/ that’s why the first condition is there to prevent that.
The second condition in the rule above checks URLs that do not end with / a trailing slash because we do not want to add a trailing slash to URLs that already have one.
If the both conditions are met then the RewriteRule is applied . The rule redirects all URLs without a trailing slash to include a slash at the end.

Is it important to include a trailing slash at the end of all URLs

If you think a URL with a trailing slash is going to rank higher and make any difference in SEO then you are doing it the wrong way. A URL with trailing slash and the one without it is considered same from SEO point of view. You can think it like a domain with with www and a domain without www. It’s not going to make any difference . It’s just how you want your URLs to appear . A URL with a / at the end looks complete so it’s completely up to you what version of URLs you want to have for your website . To maintain the the SEO you need to have just one version of your URLs. Either keep your site URLs with a slash at the end or keep them without it.

Related : How to remove trailing slash from URLs

How useful was this post?

Click on a star to rate it!

Average rating 3.8 / 5. Vote count: 99

No votes so far! Be the first to rate this post.