PaulHanak
PaulHanak

Reputation: 739

mod RewriteRule to redirect css requests to minify?

I am attempting to redirect all requests of the main stylesheet called styles.css to the minify script of min/g=css so that I may be able to work on the CSS file live and just have the server use redirect to the minify script.

Basically, this in my html file...

<link rel="stylesheet" href="css/styles.css" type="text/css">

turns into this

<link rel="stylesheet" href="min/g=css" type="text/css">

when the server requests it.

Here is my attempt so far, but it doesn't seem to be working at all. The regular css file just loads on the server..

RewriteRule ^css/styles\.css$ min/g=css

Along these same lines, I also have a fear about when I start building subdirectory pages. Does this rewrite rule need to be an "absolute path"? Thanks for any help everyone!

Upvotes: 0

Views: 760

Answers (1)

Jon Lin
Jon Lin

Reputation: 143926

Along these same lines, I also have a fear about when I start building subdirectory pages. Does this rewrite rule need to be an "absolute path"? Thanks for any help everyone!

The rewrite engine strips off the leading slash of the URI when applying rules in an htaccess file, but if the rules are in server/vhost config, then you need the leading slash. The targets (the min/g=css part of your rule) also doesn't need to be an absolute path, but if there is a leading slash, apache will apply that to the base (usually the document root). Without a leading slash, apache tries to guess whether you mean a file-path or a URI-path, sometimes it guesses wrong. If you include a RewriteBase directive, then apache will always use that as its base.

So the question here really becomes: where do you have these rules? In an htaccess file, you're only left with the question of the base. If it's in server/vhost config, you need to know the base as well as add a leading slash to the regex: ^/css/styles\.css$. Or you can be safe and make it optionsl: ^/?css/styles\.css$

Now, the base. The base is where relative paths get appended to. Your css link is this css/styles.css. If that page is loaded from, say, this URL: http://domain.com/some/path/mypage.html, then the base is http://domain.com/some/path. and the resolution of the relative path is http://domain.com/some/path/css/styles.css. In this example, your rules need to go in the directory where /some/path points to and you need a:

RewriteBase /some/path/

above your rule. Otherwise, you can simply append that base to the regex and target of your rule:

RewriteRule ^/?some/path/css/style\.css$ /some/path/min/g=css [L]

Upvotes: 1

Related Questions