简体   繁体   English

NGINX如何忽略MIME类型,JS文件中的PHP变量

[英]NGINX How to Ignore MIME Types, PHP variables in a JS file

I have a PHP script that is called as a JavaScript file in order to render some server-side variables inside of the script, ie,: 我有一个称为JavaScript文件的PHP脚本,目的是在脚本内呈现一些服务器端变量,即:

<script src="script.js.php?var1=x&var2=y"></script>

This technique works fine with Apache, but with NGINX the browser won't load the script because of strict MIME checking. 该技术在Apache上可以很好地工作,但是在NGINX上,由于严格的MIME检查,浏览器无法加载脚本。 I get this error in Safari: 我在Safari中收到此错误:

Refused to execute https://mydomain/script.js.php?var1=x&var2=y as script because "X-Content-Type: nosniff" was given and its Content-Type is not a script MIME type.

The PHP is not rendering in the JS file even though the script gives: header("Content-type: text/javascript; charset: UTF-8"); 即使脚本提供以下header("Content-type: text/javascript; charset: UTF-8"); ,PHP也不会在JS文件中呈现: header("Content-type: text/javascript; charset: UTF-8"); It seems to render a CSS file just fine using this same technique. 使用相同的技术似乎可以很好地渲染CSS文件。

I do not see add_header X-Content-Type-Options nosniff; 我看不到add_header X-Content-Type-Options nosniff; added anywhere in NGINX config (maybe I'm not finding the right file). 在NGINX配置中的任何地方添加了(也许我找不到正确的文件)。

Is there a way to disable this MIME checking feature entirely for a site? 有没有一种方法可以完全为站点禁用此MIME检查功能? Thanks! 谢谢!

This seems like a terrible way to do things. 这似乎是一种糟糕的做事方式。 It doesn't make your code very portable nor easily maintained by someone else. 它不会使您的代码具有很高的可移植性,也不会被其他人轻易维护。 You're better off using an ajax call and sending your variables as post or get that way. 您最好使用ajax调用并将变量作为post发送或以这种方式发送。 It's a little more work but definitely makes for better code. 这还需要做更多的工作,但是绝对可以带来更好的代码。

Also, this of course means you don't need to make any web server changes to make this work. 另外,这当然意味着您无需进行任何Web服务器更改即可完成此工作。

BTW - This is jQuery AJAX, adjust to usage as you see fit. 顺便说一句-这是jQuery AJAX,请根据需要调整使用量。 jQuery isn't required, this is just easier to stub out. 不需要jQuery,这更容易解决。

<script>
  var var1 = '<?php echo $var1; ?>';
  var var2 = '<?php echo $var2; ?>';
  var dataStream = { 'var1' : var1, 'var2' : var2 }; 
  $.ajax({
        method: "POST",
        url: "some.php",
        data: dataStream,
        dataType: 'json',

        }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM