2

My attempt to do this is...

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteRule \.js$ js.php [L]   ## This line is the one I tried to add
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

If I use a tag <script type='text/javascript' src='http://www.domain.net/myfile.js'></script> I would like it to go through js.php.

js.php Will handle the file using header('....'); echo file_get_contents('myfile.js');

I have tried so many things to do this, I had done this before on a project but I can't remember where now as I have to redo it :)

Hope it makes sense...

4
  • Have you your myfile.js accessible from domain.net/myfile.js ? Actually the rule RewriteCond %{REQUEST_FILENAME} !-f says that if the file is accessible then it has to be served. If this files does not exists then other rules will be applied. Commented Jul 2, 2012 at 14:07
  • I still need that for images though... or other files like PDF,MP3, etc.. Commented Jul 2, 2012 at 14:08
  • 2
    @fsehat these rules are below \.js rule and it has [L] modifier. Commented Jul 2, 2012 at 14:09
  • 1
    @Val have you tried RewriteRule ^(.*)\.js$ /js.php [L]? Commented Jul 2, 2012 at 14:10

1 Answer 1

3

You can add the following rewrite rule :

RewriteRule ^([^\.]+)\.js$ js.php [NC,L]

In place of :

RewriteRule \.js$ js.php [L]   ## This line is the one I tried to add

The result is :

http://www.domain.net/myfile.js => http://www.domain.net/js.php
http://www.domain.net/foo/bar/myfile.js => http://www.domain.net/js.php

Or you can do as follows :

RewriteRule ^([^\.]+)\.js$ $1.php [NC,L]

The result is :

http://www.domain.net/myfile.js => http://www.domain.net/myfile.php
http://www.domain.net/foo/bar/myfile.js => http://www.domain.net/foo/bar/myfile.php

Some explanations about used RewriteRule flags :

  • NC : Use of the [NC] flag causes the RewriteRule to be matched in a case-insensitive manner. That is, it doesn't care whether letters appear as upper-case or lower-case in the matched URI.
  • L : The [L] flag causes mod_rewrite to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed. This corresponds to the last command in Perl, or the break command in C. Use this flag to indicate that the current rule should be applied immediately without considering further rules.
Sign up to request clarification or add additional context in comments.

2 Comments

This worked for me :) can you update your answer with the definition of terms [NC,L] so I know what it means.
sweeet, It makes sense :) thumbs up

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.