Add Trailing Slash to URLs
Asked Answered
H

2

4

There are quite a few results for add trailing slash .htaccess on Google, but all examples I found require the use of your domain name, as in this example:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !example.php
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://domain.com/$1/ [L,R=301]

My problem is that a hard-coded domain name will not work on my local development machine. Is there a way to add trailing slashes without explicitly telling mod_rewrite the domain name?

Haggerty answered 3/11, 2009 at 15:36 Comment(1)
Looks like a question that belongs more on serverfault.com instead of stackoverflow.com.Berty
S
7

You don’t need to specify the domain, you can simply use an absolute URL path:

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

That does also make a check for the URL scheme obsolete.

Sangsanger answered 3/11, 2009 at 17:6 Comment(0)
A
3

This should work:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !example.php
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1/ [L,R=301]
Anastasia answered 3/11, 2009 at 16:15 Comment(3)
.* will match backslashes, use [^/]* insteadLong
err, in addition to I meant, such as Gumbo uses below.Long
@Oz, yes that would be better. I was merely demonstrating the use of %{HTTP_HOST}, so I went for minimal change of the originally given snippet.Anastasia

© 2022 - 2024 — McMap. All rights reserved.