Jeremy Harris
Jeremy Harris

Reputation: 24549

Htaccess Rewrite Rules for MVC

I'm having on hell of a time trying to figure out rewrite rules for my MVC microframework. I'm following the pattern url.com/:controller/:action/:params but when assets are requested (such as css, js, or png), I don't want those to be rewritten. Here is my basic folder structure:

index.php
app/
--> Config
--> Controllers
--> Layout
--> Lib
--> Models
--> Views
assets/
--> app/
    --> ...
--> vendor/
    --> ...

So if a request matches the URL pattern I described above, I want it to route to the index.php file. If it matches something in the assets folder, I want it to allow it to go through unaffected.

This is the current .htaccess I've created and have been altering things back and forth:

RewriteEngine On
RewriteBase /

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f 
RewriteCond %{REQUEST_URI} !\.(jpg|png|js|css)$

RewriteRule ^([^/]+)(/)([^/]+)(/)(.*) index.php?controller=$1&action=$3&params=$5 [L]
RewriteRule ^([^/]+)(/)(.*) index.php?controller=$1&action=$3&params= [L]
RewriteRule ^([^/]+)(/) index.php?controller=$1&action=index&params= [L]
RewriteRule ^([^/]+) index.php?controller=$1&action=index&params= [L]

The url pattern matches fine, but for some reason any requests to the assets folder also get rewritten. Doing some various tests, I've found that the L flag, which as I understand it means "last", doesn't stop it from processing further rewrites.

I know other people had to have dealt with this issue before as MVC is such a common pattern. Can anybody point out what I am doing wrong?

Upvotes: 0

Views: 2942

Answers (1)

Ferry Kobus
Ferry Kobus

Reputation: 2029

Try excluding that folder:

RewriteCond %{REQUEST_URI} ^/assets.*$
RewriteRule ^(.*)$ - [L,NC]

And I use:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

Instead of:

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

Upvotes: 1

Related Questions