Basic - replace ".htm" with a trailing slash using htaccess

This is a basic question.

Replace “.htm” at the end of a requested URL with a trailing slash (“/”).

Something that would send the requested url “” to “”, and continue that scheme no matter how deep.” would go to”.

I’m not sharp with grouping text in htaccess and I don’t know how to reposition it. I’d imagine it’s something like

RewriteCond %{HTTP_HOST} ^\.htm)$ [NC]
RewriteRule ^(.*)$$1/ [L,R=301]

But I just don’t know how to make it work.

RewriteCond %{HTTP_HOST} ^\\.htm)$ [NC]

%{HTTP_HOST} only captures the host, like,,, etc, and does not contain the URL that was actually requested.

The only thing you need is a RewriteRule.
The (\.htm) you had above is a step on the right track, you just need to implement it in the RewriteRule. Although it shouldn’t be in parentheses, because you don’t want to re-use it in the new URL. You want to rid of it, so there’s no need to capture it :slight_smile:

Try if you can come up with the right rule using this info.
As a last hint, the URL to rewrite to ($1/) and the flags ([L,R=301]) you had are correct, the only bit that’s wrong is the ^(.*)$

Scallio, thanks much for pointing me in the right direction. This is what I came up with:

RewriteRule ^(.+)\.htm$$1/ [L,R=301]

It seems to work. If there’s a better way to do this, or if I left anything out, I want to know. I’m always adamant about covering all of the bases - at least trying to.

Very nice, you even managed to stay clear from the root of all evil - the ANYTHING atom: (.*)

But, you went to it’s slightly less evil twin brother - (.+)

Not to worry, it’ll work fine, but there is a better solution - provided none of your URLs contain any other dot than the dot in .htm

The thing is, (.*) and (.+) are greedy, which means they will blindly eat up anything they see.
If your URLs never contain any other dot than the dot in .htm you could use a lazy atom that will match anything except for a dot.

That is – ([^.]+)

Both (.+) and ([^.]+) will work, it’s just a matter of style and ([^.]+) is a bit more stylish :slight_smile:

Style is definitely secondary, but as long as it’s functional, I’m up for letting it have a little bit of style. The advice and knowledge you’ve shared is hugely appreciated, thank you.


You forgot to mention that adding a USELESS / at the end of a file changes the directory level for relative links and should also require the use of Options +MultiViews - both :nono: IMHO!




I moved your post to a new thread to prevent hijacking of this OP’s thread.