php.htaccesshttp-redirectsubdirectoryredirect-loop

Subdirectory not redirecting to index


I used the following code in my .htaccess file.:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

After using it, it finally allowed me to remove file extensions, my goal,
but then subdirectories no longer redirected to their respective index files, instead showing just 'Forbidden' and '404' messages.

I then tried to make manual redirects in the .htaccess:

Redirect 301 /subfolder http://www.domain.com/subfolder/index

Which then got me stuck in redirect loops, and even after removing them in the source code, they have carried on. I should also point out that I have almost no experience in using .htaccess.


Solution

  • Welcome to the wonderful world of testing with permanent redirects: Make a mistake, and it continues making the error until you clear the browser cache.

    First of all, remove the redirect, and clear the cache of your browser. Second of all, imagine that your rules are applied to every request, not just the requests you want to change.

    The problem you identified was a request to a directory matching your rule, then getting rewritten. Requests to http://domain.com/sub/ would be rewritten to http://domain.com/sub/.php. Now that is not anything that exists. The only thing saving you from infinite recursion is your check for dots in the url.

    So, how do we fix that? Well, we check if the requested file is not a directory to start of. Now we don't rewrite the url if it is a directory, and DirectoryIndex takes care of the rest. To prevent infinite recursion, you can test if the url already ends with .php, but in this case you already took care of that.

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^\.]+)$ $1.php [NC,L]