Claudiu
Claudiu

Reputation: 3261

.htaccess redirect files with certain paths to another directory

This might seem a bit basic and something that's been asked quite a lot around here, but I have a small .htaccess problem (mod_rewrite).

I'm working on a MVC framework for PHP (like everybody else...) and all traffic goes through index.php which then routes to the required controller and method. All that goes well. The structure is roughly something like this:

For an URL like myapp.com/css/ I need o load the CSS controller, index function. But for URLs like myapp.com/css/style.css I need to fetch the file from the public/css/directory

I'd hate writing /public/ for each file I want to include, so basically I need to redirect all traffic to /public/ if it's an actual file and keep the normal rewriting rule for all other URLs. I'm planning to use this in production and it would be much easier to let frontend developers do their stuff the way they normally do it and then just copy paste stuff into place instread of going through CSS to modify paths and such.

I came up with this:

RewriteEngine on

RewriteRule ^(img|css|js|assets)/(.*).([a-z]{3})$ public/$1/$2 [L,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

But it has some obvious flaws. I don't mind having to set directories in the first regex, but checking that the path is a file the way I do seems rather unreliable. Using RewriteCond to check that it's a file didn't work for some reason and I think this method can fail for URLs like myapp.com/img/this-is-actually-an-article.aaa Of course, extensiuons can also be longer than 3 characters and I need to check that that's safe as well.

What's the best way to go about this? How do you guys ussually do it? Or is this a wrong approach from the very begining?

Upvotes: 0

Views: 1244

Answers (1)

Halcyon
Halcyon

Reputation: 57721

The -f isn't working because the requested file is /css/style.css whereas the file on disk is /public/css/style.css.

I see no problem with declaring some predefined namespaces that you can't use in your application (like img, css, js, assets).

Eventually I think you will move to a situation where plugins for your framework can no longer decide where their resources are, the framework should decide it for them and possibly even load it for them. This resolves all your current issues as no plugin code will ever need to know anything about URLs. Regardless of your rewriting strategy I think this is something to aspire to.

Upvotes: 1

Related Questions