RewriteRule conflict and trailing slash

We are migrating a website to our cPanel infrastructure. The customer hosted the website on his own infrastructure using Nginx. He sent to us his Nginx configuration files and we converted them to Apache Rewrite rules. The final result (showing only the relevant lines) looks like this:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ouvidoria/$ /ouvidoria/index.php
RewriteRule ^([^/\.]+)/?$ index.php?id=$1 [L]
RewriteRule ^news\/(.*)/?$ noticias.php?id=$1 [L]

Everything work as expected, except for one page, which is /ouvidoria. This specific page has a directory with the same name on public_html, so the RewriteRule points to the ouvidoria/index.php file. The problem is that for some reason when we access the /ouvidoria URL we get redirected to /ouvidoria/?id=ouvidoria, which seems to be falling on the penultimate rule. So this is the first problem to be solved.

The second is that we can access the URL with a trailing slash (/ouvidoria/) and it won't append ?id=ouvidoria, but, the website was developed in a way that the side menu is loaded accordingly to the URL. It will only load without a trailing slash. Even if we remove the problematic rule from the first problem (which is not a solution, because it is needed in other pages), it redirects /ouvidoria to /ouvidoria/, thus failing to load the menu.

Any help on how to make these rules work will be appreciated.

EDIT:

The only problem that remains is the redirect from /ouvidoria to /ouvidoria/. Network tab screenshot:

Network tab

Redirect details:

Redirect details


Solution 1:

Updated answer to address "redirect to subdirectory" issue. Try the following set of directives:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ouvidoria/?$ /ouvidoria/index.php [L]
RewriteRule ^([^/\.]+)/?$ index.php?id=$1 [L]
RewriteRule ^news\/(.*)/?$ noticias.php?id=$1 [L]

By removing the RewriteCond %{REQUEST_FILENAME} !-d, Apache doesn't check if a directory with the requested resource exists. This might help with your issue.


Original answer:

It has been a while since I have worked with Apache rules, but I think the following change would help you achieve your goal:

Replace

RewriteRule ^ouvidoria/$ /ouvidoria/index.php

with

RewriteRule ^ouvidoria/?$ /ouvidoria/index.php [L]

The original version of the rule matches only /ouvidoria/ URI. Therefore the request reaches the second RewriteRule, which causes behavior like you described.

The fixed version of the rule matches both /ouvidoria/ and /ouvidoria.