jeffjenx
jeffjenx

Reputation: 17467

mod_rewrite existing directory changes URL in address bar

I'm trying get mod_rewrite to redirect all requests that aren't files to index.php so I can handle routing for clean URLs.

<IfModule mod_rewrite.c>  
    RewriteEngine On

    # Route requests to index.php for processing
    RewriteCond %{REQUEST_FILENAME} !-f

    RewriteRule ^(.+)$ index.php?request=$1 [QSA,L]
</IfModule>

For some reason, when I access an existing directory without a trailing slash, the address bar is reformed to include a trailing slash and the query string, which is not very clean.

I'm able to improve this by changing the RewriteRule to ^(.+)/$ and adding RewriteBase /. However, this directs all URLs to one with a trailing slash. Not a big deal, but not how I want it.

If, for example, /test/folder exists and I go to that directly, I'd like the address bar to display that, instead of displaying /test/folder/ or /test/folder/?request=/test/folder.

Upvotes: 1

Views: 514

Answers (2)

jeffjenx
jeffjenx

Reputation: 17467

Well, persistence pays off. jerdiggity's answer provided insight, which led to further experimentation and research. Eventually, I came to the conclusion that there must be something built into Apache that is rewriting the trailing slash.

As jerdiggity suspected, all of the Rewrite logic was accurate, but something called a DirectorySlash Directive in another directory-related Apache module, mod_dir, was adding the trailing slash.

Apparently, you can simply disable this directive, which I added to the top of my logic:

DirectorySlash Off
RewriteEngine On
...

Upvotes: 1

jerdiggity
jerdiggity

Reputation: 3665

I'd give this a try:

DirectoryIndex index.php
<IfModule mod_rewrite.c>  
    RewriteEngine On
    # I tested this inside a subdir named "stack", so I had to uncomment the next line 
    #RewriteBase /stack

    # Route requests to index.php for processing

    # Check if the request is NOT for a file:
    RewriteCond %{REQUEST_FILENAME} !-f

    # Check if the request IS for an existing directory:
    RewriteCond %{REQUEST_FILENAME} -d

    # If all criteria are met, send everything to index.php as a GET request whose
    # key is "request" and whose value is the entire requested URI, including any
    # original GET query strings by adding QSA (remove QSA if you don't want the 
    # Query String Appended): 
    RewriteRule .* index.php?request=%{REQUEST_URI} [R,L,QSA]
</IfModule>

If this doesn't happen to work, please let me know what else is in your .htaccess file because for the most part, it looks like it should be working. Should. ;)

Upvotes: 1

Related Questions