Search code examples
javascriptapachevirtualhostreverse-proxyhttpd.conf

reverseProxy: how to change content in embedded JavaScript file


I use Apache HTTP 2.4 as a reverse proxy. My configuration works fine except one thing:

  • I would like to change a string content (url) in an embedded JavaScript file

This is my actual virtual host configuration:

<VirtualHost web.mydomain.com:80>
      ServerName web.mydomain.com
      ServerAlias web.mydomain.com

      DocumentRoot "..."
      ...

      RewriteEngine On
      RewriteCond %{REQUEST_METHOD} OPTIONS
      RewriteRule ^(.*)$ $1 [R=200,L]
      
      #Options -Indexes
      #ProxyRequests On
      #ProxyPreserveHost Off

      # Web App
      ProxyPass /hello http://middleware.mydomain.com:8082/hello-world-0.0.7
      ProxyPassReverse /hello http://middleware.mydomain.com:8082/hello-world-0.0.7
      
      AddOutputFilterByType SUBSTITUTE text/html
      Substitute "s|hello-world-0.0.7|hello|ni" 
</VirtualHost>

Could you please help me?


Solution

  • Usually, you should be able to configure the external URL in your application server, thereby eliminating the need to do the substitution in your Apache server. Such a configuration would be more efficient.

    Did you validate in your browser that the returned Content-Type matches your filter? You indicate a Javascript file but filter for text/html. (e.g. Chrome: open Developer tools > navigate to the page > open Network tab > click on the resource that needs substitution > Look for the Content-Type header in the response headers). The Content-Type header should match your filter.

    If it still does not work, it is likely that the application server returns gzipped content (check for Content-Encoding: gzip in the response headers). In that case, it makes sense that substitution won't work.

    To work around that, add the following directive in your Apache configuration:

    RequestHeader unset Accept-Encoding
    

    Please note that this results in a performance penalty since more data needs to be sent across the network. I won't recommend this solution in a production environment since it applies to all requests for the current Virtual Host. If you only need to use substitution for a single file, I recommend wrapping the AddOutputFilterByType, Substitute and RequestHeader directives in a block, so that Apache only does the additional work for that file:

    <Location "/hello/path/to/your/javascript/file.js">
      RequestHeader unset Accept-Encoding
      AddOutputFilterByType SUBSTITUTE text/html
      Substitute "s|hello-world-0.0.7|hello|ni" 
    </Location>