matt
matt

Reputation: 44303

htaccess: add trailing slash to specific case only

quick question regarding my .htaccess file

I want to forward https://myurl.com/en to https://myurl.com/en/ with a trailing slash.

This is my try so far.

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

What am I doing wrong here? Thanks for your help?

Upvotes: 2

Views: 581

Answers (2)

Gillsoft AB
Gillsoft AB

Reputation: 4225

You can always activate DirectorySlash for a specific location:

<Location "/en">
  DirectorySlash On
  FallbackResource /index.php
</Location>

I didn't spend that much time on this issue, but you want to read the warning about it in the link above. Or you can use the alternative solution:

RewriteEngine On
RewriteCond %{REQUEST_URI} ^/en$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

If problems with relative urls for images etc. try adding the following to your page header:

<head>
 <base href="/" />
<head>

Restart apache in order for the changes to take effect. If WordPress is used pay attention to the order of execution. All the redirect rules must be located before routing rules. The WordPress rules route everything to index.php.

Upvotes: 1

Googlian
Googlian

Reputation: 6723

To ensure all URLs have a trailing slash.

The below rule will forward https://myurl.com/en to https://myurl.com/en/ with a trailing slash at the end.

https://myurl.com/en to https://myurl.com/en/

Setting trailing slash globally for all of your URLs in your domain name.

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

The below rule is applicable only for a specific URL segment:

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

Clear the browser cache

Once you made any changes in your .htaccess file, you have to clear your browser cache before try it again or open through a new incognito browsing mode to test your changes, most of the modern browsers usually cache the webpage so you cannot see the action unless you cleared the browser cache.

Upvotes: 0

Related Questions