skip to Main Content

I want to modify an .htaccess file to do 2 things:

  • Force the addition of a slash at the end of each URL
  • Replace the excess slashes (2 and more) by 1 single slash.

Here is a set of URLs and their expected result:

https://www.mywebsite.io/fr > https://www.mywebsite.io/fr/
https://www.mywebsite.io/fr/register > https://www.mywebsite.io/fr/register/
https://www.mywebsite.io/fr/register// > https://www.mywebsite.io/fr/register/
https://www.mywebsite.io/fr////register > https://www.mywebsite.io/fr/register/
https://www.mywebsite.io/fr/register///other////// > https://www.mywebsite.io/fr/register/other/

I manage to do the first step which is to force a final / but I cannot replace the extra /.

Can you help me with this problem?

Here is the content of my .htaccess file

Options +FollowSymlinks
RewriteEngine On

## Force HTTPS
RewriteCond %{HTTPS} !on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}/$1 [L,R]

## Force slash
RewriteCond %{REQUEST_URI} /+[^.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [L,R]

## Remove repeated slashs
#RewriteCond %{REQUEST_URI} ^(.*)/{2,}(.*)$ [N]
#RewriteRule (.*) %1 [R,L]

RewriteRule (.*)/{2,}(.*) $1/$2 [N]


RewriteRule ^(fr|en){1}(/?)$ content/index.php?lang=$1 [L]
RewriteRule ^(fr|en){1}(/){1}(registration){1}(/?)$ content/registration.php?lang=$1 [L]

2

Answers


  1. With your shown samples, could you please try following. I have also fixed your small issues of missing flags too in your question. Please make sure you clear your browser cache before testing your URLs.

    Options +FollowSymlinks
    RewriteEngine On
    
    ## Force HTTPS
    RewriteCond %{HTTPS} !on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}/$1 [L,R]
    
    ## make slashes to 1 at last or uri, in between slashes will be automatically moved to single slash.
    RewriteRule ^([^/]*)(?:/+)$ %{REQUEST_URI}/ [L,R=301]
        
    RewriteRule ^(fr|en)/?$ content/index.php?lang=$1 [NC,L]
    RewriteRule ^(fr|en)/(registration)(/?)$ content/$2.php?lang=$1 [NC,L]
    
    Login or Signup to reply.
  2. Have it like this: (see comments inline)

    Options +FollowSymlinks
    RewriteEngine On
    
    ## add https and trailing slash in same rule
    RewriteCond %{HTTPS} !on [OR]
    RewriteCond %{REQUEST_URI} !/$
    RewriteRule ^(.*?)/?$ https://%{HTTP_HOST}/$1/ [R=301,L,NE]
    
    ## Remove repeated slashs
    RewriteCond %{THE_REQUEST} s[^?]*//
    RewriteRule ^.*$ /$0 [R=301,L,NE]
    
    RewriteRule ^(fr|en)/?$ content/index.php?lang=$1 [L,QSA]
    RewriteRule ^(fr|en)/registration/?$ content/registration.php?lang=$1 [L,QSA]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search