How to redirect a URL always with bar (/) at the end?

Asked

Viewed 1,535 times

1

I have that code:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteRule . /index.php [L]
</IfModule>

When I type http://localhost/path I’d like him to redirect to: http://localhost/path/

I would like to do this without changing my base code:
In the code above when you put http://localhost/path it redirects to index.php (I want to keep this).
I want my code to be flexible to accept any URL changes and to accept both http and https.
I also want it to detect the folder my site is in if it changes folder. Example:
Of localhost/ for localhost/www/site
And I don’t want it to ignore the path of existing files and directories.

How to do this?

1 answer

4


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

The lines with !-f and !-d make the rule not work if it is an existing file path or directory.

You need to see in your practical case if this is what you want when dealing with images and static files. Extra rules may be required depending on the desired result.

  • Wouldn’t it be more compatible? What if I want to put https on my website? What if my website’s domain changes?

  • the RewriteRule you can change as you like, and leave without the protocol and the domain. the important thing is the $1/.

  • So you can stay like this: RewriteRule ^(.*)$ $1/ [L, R=301]?

  • Bacco you could improve the code to make it more flexible?

  • @Rowaraujo would be nice if you edit the question and add the details you need (just try not to change the original meaning of it, but add examples of input Urls and their desired conversions)

  • Pronto Bacco!!!

  • @Rowaraujo updated. I actually just removed the protocol and URL, and started from / .

  • Just one more thing: My site is on localhost, but it’s on localhost/www/site and when I put some path it redirects to localhost/path

  • @Rowaraujo se vc acesso por http://127.0.0.1/path ele faz o que?

  • He accesses another folder, and my website is on localhost/www/site/

  • And I want it to all path it redirects to the file index.php that is in the root folder. How does my code go up in the question.

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.