【问题标题】:How to set some PHP headers in a .htaccess file如何在 .htaccess 文件中设置一些 PHP 标头
【发布时间】:2014-07-13 14:15:43
【问题描述】:

所以我的一些 PHP 文件中有这些标头:

<?php
    header('Content-Type: text/html; charset=UTF-8');
    header('Content-Style-Type: text/css');
    header('Content-Script-Type: application/javascript');
    header('HTTP/1.1 200 OK');
    header('Content-language: en-US');
    header('X-Powered-By: PHP/5.2.17');
    header('Last-Modified: Tue, 01 Jan 2013 00:00:00 GMT');
    header('Cache-Control: no-store, no-cache, max-age=0, must-revalidate');
    header('Pragma: no-store, no-cache, max-age=0, must-revalidate');
    header('Expires: Tue, 01 Jan 2013 00:00:00 GMT');
?>

如何在我的 .htaccess 文件中设置它们? (应该只针对特定文件),这是我目前得到的:

<FilesMatch "^(index.php|about.php|contact.php)$">
    # HTTP Headers should be set in here
</FilesMatch>

【问题讨论】:

  • 可以在 .htaccess 中定义过期和缓存等内容,但 HTTP 200 等内容不应该。为什么要这样做?
  • 指令的名字叫Header ;-P

标签: php .htaccess http-headers


【解决方案1】:

您需要安装 mod_headers,否则您可能会收到错误 500。您可以将 headers 的设置包装在一个条件中以检查 mod_headers 是否存在。

<FilesMatch "\.(html|htm|js|css)$">
    <ifModule mod_headers.c>
        Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
        Header set Expires "Thu, 1 Jan 2015 05:00:00 GMT"
    </ifModule>
</FilesMatch>

您也可以取消设置标题。例如,如果您使用负载平衡器,则可以以您不想向应用程序公开的自定义标头的形式传递真实的访问者 IP。

Header unset Real-Visitor-IP

除了过期和 etag 以及特定于网络服务器的自定义标头之外,您不应在网络服务器级别篡改标头。它们中的大多数应该在应用程序级别进行管理,如果您将更改的内容类型传递给它们,您将阻止某些框架正常工作。

【讨论】:

  • mod_headers 肯定安装在我的服务器上。这些也不是所有的标题,是吗?我只想把上面的 PHP 脚本转换成 Apache 指令...
  • 这只是一个例子。是的,您可以使用 mod_headers 设置所有这些 PHP 指令,但除了过期、etags、缓存之外,这就是应用程序的工作。如果您手动将标头状态设置为 200,您的应用程序将无法响应简单的 404 not found 请求。
  • 好的,那么Content-Style-Type, Content-Script-Type and Content-language呢?
  • 这些是 HTML 4.01 时代的后备方案。我认为它们在现代浏览器中不再有用。此外,它们只有在 html 文档上声明时才有意义。样式表不需要默认的 Content-Style Type,因为它本身就是样式。
  • 啊,好老的基于 DTD 的标记语言...我现在使用 HTML5,但我想保持对 IE 6 等浏览器的兼容性...
猜你喜欢
  • 2012-03-07
  • 2019-04-26
  • 2011-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-25
  • 2018-08-08
  • 1970-01-01
相关资源
最近更新 更多