1

So I am trying to force javascript files to reload whenever we as developers update the files. In order to do this we are using the answer found here https://stackoverflow.com/a/7671705/805779 and we think this will work great however I am not sure how to do the mod rewrite. So here is the link I have

www.mysite.com/js/v1/myjs.js

I need to change it to

www.nysite.com/js/myjs.js

This is what I have so far but it is not working

<IfModule mod_rewrite>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^/js/(.*)$/(.*)$ js/$2 [L,NC,R]
</IfModule>

After some more testing I found my main issue was not adding .c to my IfModule, with that in mind the following is "partially" working

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^/css/(.*)/(.*)$ /css/$2 [L,NC,R]
    RewriteRule ^/js/(.*)/(.*)$ /js/$2 [L,NC,R]
</IfModule>

This works for my classic example

www.mysite.com/js/v1/myjs.js => www.nysite.com/js/myjs.js

However this does not work if more then one variable are involved. aka

www.mysite.com/js/v1/min/pages/myjs.js 

My version number v1 will always be directly after the root folder so js/v1 or css/v1 and I want to remove the v1 and keep everything after it

Community
  • 1
  • 1
CMOS
  • 2,425
  • 4
  • 39
  • 69
  • Why not just version control the file (i.e. `myjs_v1.js`, `myjs_v2.js`, etc.)? This is typically a more scalable strategy, especially when you want to start doing things like storing your static assets on a CDN. This also allows you to set really long expires headers on that content, aiding in browser-side caching. It also make rollbacks really easy (you just change the HTML to refer back to old file and browser will do the right thing). – Mike Brant May 12 '15 at 18:28
  • Because as stated in the answer I linked above some browsers and proxies will not read ? variables and cause users to still have outdated files. This way guarantees that it will pull the new file since it is in the link structure. – CMOS May 12 '15 at 18:33
  • I said nothing about passing pare eyes to disrupt the cache, just changing the actual file name. – Mike Brant May 13 '15 at 02:45

1 Answers1

0

You can use this single rule for this redirect:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^/?((?:css|js))/v\d+/(.+)$ /$1/$2 [L,NC,R]
</IfModule>
anubhava
  • 664,788
  • 59
  • 469
  • 547
  • This seems to do nothing. Would I need to do anything else? – CMOS May 12 '15 at 18:46
  • This worked on my Apache and redirected `www.localhost/js/v1/min/pages/myjs.js` to `www.localhost/js/min/pages/myjs.js` thus removing `/v1` from URL. Do you have other rules also? Try commenting out ` – anubhava May 12 '15 at 18:47
  • 1
    This worked great! I had a type in my code and I was not adding v in front of my version. ! – CMOS May 12 '15 at 18:58
  • Glad it worked out. Strangely someone downvoted my working answer without any comment. – anubhava May 12 '15 at 19:01