Search code examples
javascriptphp.htaccessmod-rewriteunobtrusive-javascript

Javascript/jquery does not load with mod_rewrite on


I'm still struggling with the workings of mod_rewrite. So my test page request works well until I turn on mod_rewrite.

This is the .htaccess directive

RewriteRule     ^.*$    scripts/index.php

And the target PHP file has these:

<head>
    <script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js" ></script>
    <script type="text/javascript" src="/libraries/colorbox-master/jquery.colorbox-min.js" ></script>
    <script type="text/javascript" src="/js/index.js" ></script>
    <title>index.php</title>
</head>

And just testing out the index.js file with:

console.log('Hello world');

I get this browser console error messages with mod_rewrite turned on:

Resource interpreted as Script but transferred with MIME type text/html: "http://web3.loc/js/index.js". index.php:7
Uncaught SyntaxError: Unexpected token <                    index.js:2

Solution

  • If you preceed your rule with

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    

    it will not be evaluated if an existing file or directory is requested and the requested ressource will be served instead of your index.php.

    See http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html