dodov
dodov

Reputation: 5844

.htaccess rewrite URL to unminified version of file (if it exists) based on query string

I want to serve the unminified version of any file with nomin in its URL.

For example, if I request:

http://localhost/foo/bar.min.js?nomin

I should receive the file:

http://localhost/foo/bar.js

However, I want that to happen only if the file exists.

This is what I have in my .htaccess file:

RewriteCond %{QUERY_STRING} nomin
RewriteCond %{REQUEST_URI} (.*)\.min(\..*)
RewriteCond %{DOCUMENT_ROOT}/$1$2 -f
RewriteRule (.*)\.min(\..*) $1$2 [L,QSA,NC]

However, it doesn't work. If I remove the line where I check if the file exists:

RewriteCond %{DOCUMENT_ROOT}/$1$2 -f

It starts working, but may point to non-existent files.

I tried:

What am I doing wrong?


Side question: Is there a way to change my RewriteCond and RewriteRule such that I don't have to write (.*)\.min(\..*) twice?

Upvotes: 1

Views: 119

Answers (1)

anubhava
anubhava

Reputation: 785781

This should work for you:

RewriteCond %{QUERY_STRING} ^nomin$ [NC]
RewriteCond %{REQUEST_URI} ^(.+)\.min(\.[^.]+)$ [NC]
RewriteCond %{DOCUMENT_ROOT}/%1%2 -f
RewriteRule ^ %1%2 [L,NC]

Use %1, %2 instead of $1, $2 for values being captured from RewriteCond

Upvotes: 1

Related Questions