开发者

Redirect script.js to script.php

开发者 https://www.devze.com 2023-01-08 06:31 出处:网络
I have some javascript that is generated by PHP. Currently I am including the javeascript in the html using

I have some javascript that is generated by PHP. Currently I am including the javeascript in the html using

<script type="text/javascript" src="js/script.php">

But I want to use

<script type="text/javascript" src="js/script.js">

Now script.js does not exist, but I want it开发者_开发问答 to redirect to script.php without the user knowing.

Can this be done with .htaccess?


If your web server supports mod_rewrite, you could do something like this:

RewriteEngine On

RewriteRule ^js/script\.js$ js/script.php

If you have more than one script, you could generalize that RewriteRule by using a backreference from the test pattern:

RewriteRule ^js/(.*)\.js$ js/$1.php


In the parent directory you could have a .htaccess which maps all asset files to the relevant php file.

RewriteEngine on
RewriteRule ^js/(.*)\.js$ js/$1.js.php     
RewriteRule ^css/(.*)\.css$ css/$1.css.php

notice I have kept the file extension for better readability.

Files

htdocs
    mysite
        assets
            .htaccess
            js->
                script.js.php ( http://locahost/mysite/assets/js/script.js )
            css->
                style.css.php ( http://locahost/mysite/assets/css/style.js )

Headers

By default the files will be outputted as php, you will have to change the content type header to the correct type(js,css,txt,xml, etc).

You might also want to disable the files from being cached as they most probably change frequently.

You can either do this in all the php files or in the .htaccess file.

PHP

content type

js/*.js.php -> header("Content-type: text/javascript");
css/*.css.php ->header("Content-type: text/css");

cache

*.php -> header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
*.php -> header('Pragma: no-cache'); // HTTP 1.0.
*.php -> header('Expires: 0'); // Proxies.

.htaccess

content type

<FilesMatch \.js.php$>
  Header set Cache-Control "no-transform"
  Header set Content-Type "application/javascript; charset=utf-8"
</FilesMatch>
<FilesMatch \.css.php$>
  Header set Cache-Control "no-transform"
  Header set Content-Type "text/css; charset=utf-8"
</FilesMatch>

cache

<IfModule mod_headers.c>
  Header set Cache-Control "no-cache, no-store, must-revalidate"
  Header set Pragma "no-cache"
  Header set Expires 0
</IfModule>


If you just want your script src to end in ".js" you could always leave it as a .php file and link it in like this:

<script type="text/javascript" src="js/script.php?name=script.js">

This technique is commonly used with php or other scripts which generate images:

<img src="images/thumbnailer.php?x=foo.jpg">

This way if the browser tries to determine the type of file by the "extension," it will be "tricked" into using the right format.

0

精彩评论

暂无评论...
验证码 换一张
取 消