Apache Proxy with CORS headers

You want to have your JavaScript application access a remote API but that remote API does not have CORS headers. What to do?

Instead of pointing to that remote API, point to a location on an Apache server that you have control of, have it connect to that remote API for you, and also add the CORS headers so JavaScript is happy.

Apache can proxy, or hand off the API request for you while also injecting the CORS header Access-Control-Allow-Origin to that remote API response.

Requirements:
Apache mod_proxy
Apache mod_headers

# Proxy for BaseServer
<LocationMatch "/api">
   ProxyPass http://remote-server.com:8000/api/
   Header add "Access-Control-Allow-Origin" "*"
</LocationMatch>

Now instead of pointing my JavaScript to http://remote-server.com:8000/api/, I point it to my Apache server at /api/ and that will serve the data from http://remote-server.com:8000/api/ with the CORS header.

http://enable-cors.org/server_apache.html

If you are using mod_rewrite along with this, you might need the [P] flag which tells mod_rewrite to handle the request with mod_proxy.

https://httpd.apache.org/docs/2.4/rewrite/flags.html


Posted

in

,

by

Tags:

Comments

3 responses to “Apache Proxy with CORS headers”

  1. Karim Avatar
    Karim

    Hello Chris, thank you for the very useful post. For some reason this was the only post I found that tackled this exact problem. I have a question, what if I want to write a URL that has https in the proxypass instead of http? When I do so I get a 500 Internal server error.
    Thank you.

    1. Chris Carey Avatar

      You may need mod_ssl and the directive next to ProxyPass:

      SSLProxyEngine On

  2. Vaclav Avatar

    Hi,

    Thank you very much for this post. This solution is very handy with a client-side javascript app.
    The only disadvantage is that one needs an access to httpd.conf as this one needs to be edited.

Leave a Reply

Your email address will not be published. Required fields are marked *