【问题标题】:Prevent Apache custom error pages on JSON responses在 JSON 响应中防止 Apache 自定义错误页面
【发布时间】:2016-09-02 20:26:48
【问题描述】:

我正在使用一个同时提供 HTML 内容和 JSON API 的应用程序。使用 Apache,我为 HTML 内容创建了自定义错误页面。配置使用类型映射来根据浏览器语言指定不同版本的错误页面。

问题在于 JSON API 返回错误时。该响应(包含一些描述错误的 JSON 元素)正在替换为 HTML 错误页面。如何将 Apache 配置为忽略 JSON 响应,不加修改地返回它们?

这是 JSON 请求的接受标头:

Accept:application/json, text/javascript, */*; q=0.01

以下是来自应用程序 (Tomcat) 的响应标头:

Content-Length:23
Content-Type:text/json;charset=UTF-8
Date:Fri, 02 Sep 2016 15:34:03 GMT
Server:Apache-Coyote/1.1

但这里是 Apache 返回的响应标头:

Accept-Ranges:bytes
Connection:close
Content-Language:en
Content-Length:7628
Content-Location:404.en.html
Content-Type:text/html; charset=UTF-8
Date:Fri, 02 Sep 2016 15:14:08 GMT
Server:Apache
TCN:choice
Vary:negotiate,accept-language

这是我的配置,供参考:

httpd.conf

Alias /errors/ "/var/www/errors/"

<IfModule mod_negotiation.c>
<IfModule mod_include.c>
    <Directory "/var/www/errors">
        AllowOverride All
        Options IncludesNoExec
        AddOutputFilter Includes html
        AddHandler type-map var
        Order allow,deny
        Allow from all
        LanguagePriority en es de fr pt
        ForceLanguagePriority Prefer Fallback
    </Directory>
    ErrorDocument 404 /errors/404.var
    ErrorDocument 403 /errors/403.var
    ErrorDocument 500 /errors/500.var
    ErrorDocument 502 /errors/500.var
    ErrorDocument 503 /errors/maintenance.var

</IfModule>
</IfModule>

这是 .var 文件之一的示例。 404.var

URI: 404

URI: 404.en.html
Content-type: text/html
Content-language: en en-US

URI: 404.en-GB.html
Content-type: text/html
Content-language: en-GB

URI: 404.fr.html
Content-type: text/html
Content-language: fr

URI: 404.de.html
Content-type: text/html
Content-language: de

URI: 404.es.html
Content-type: text/html
Content-language: es

URI: 404.pt.html
Content-type: text/html
Content-language: pt

这里是另一个 .conf 文件中的一些附加配置,以确保我包含所有相关内容:

ProxyRequests Off
ProxyPreserveHost On
ProxyErrorOverride On

<Proxy *>
    Order deny,allow
    Allow from all
</Proxy>

ProxyPass /server-info !
ProxyPass /server-status !
ProxyPass /errors !

ProxyPass / http://localhost:7002/
ProxyPassReverse / http://localhost:7002/

<Location />
    Order allow,deny
    Allow from all
</Location>

【问题讨论】:

    标签: json apache


    【解决方案1】:

    这是我对带有以下标头的请求所使用的:

    Accept:application/json, text/javascript, */*; q=0.01 
    
    <If "%{HTTP_ACCEPT} =~ /json/">
         ProxyErrorOverride Off
    </If>
    

    【讨论】:

      【解决方案2】:

      一个更简单的解决方案:

      将所有返回 json 的脚本保存在单独的目录中,例如 /ajax/api,然后像这样配置 Apache:

      ProxyErrorOverride On
      
      <Directory "/path/to/ajax/or/api">
          ProxyErrorOverride Off
      </Directory>
      

      【讨论】:

        猜你喜欢
        • 2014-02-28
        • 2013-06-08
        • 2014-02-22
        • 2011-06-07
        • 2019-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多