Search code examples
phpapache.htaccessmod-rewritexampp

Prevent redirect of "path" to "path/" in apache server


I'm using XAMPP to create a local server and noticed that when I visit something like localhost/path I get redirected (301) to localhost/path/

The problem is that I'm trying to send a POST request to localhost/path and after being redirected it turns into a GET request.

Is there a way to prevent such redirect from happening?

It may be worth mentioning that I'm using mod_rewrite in a .htaccess file, but even with all the rules disabled the behaviour remains the same.

Edit

I realized that I had a folder called path and renaming it prevented localhost/path from redirecting.

Still, is there a way to avoid such behivour (not getting a 301 to localhost/path/) when the folder exists with the same name?


Solution

  • You can use a combination of DirectorySlash directive and a regular regex that removes the trailing slashes:

    RewriteEngine On
    
    DirectorySlash Off
    RewriteRule ^(.+?)/$ /$1 [R=302,NE,L]
    

    Example: Assumig that path is an existing folder and foo doesn't exist:

    • /path/ => /path
    • /path/foo/ => /path/foo
    • /foo/ => /foo
    • /path stays the same
    • /path/foo stays the same
    • /foo stays the same