3

I need to enable cross-domain AJAX requests on my site, while limiting the cross-domain access to a particular template.

This template is in its own template group, so the requests from the script would look something like this:

domain.com/embeddable-content

I have this in my .htaccess file:

<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>

But this grants access across the entire domain. How would I go about restricting access to the single template?

I've googled around, but this is slightly out of my bailiwick, and I figure there my be complications because of EE's file structure (or lack thereof).

1

3 Answers 3

6

If you're only allowing access to a single template, I'd imagine the easiest way would be to use PHP's header to add

header('Access-Control-Allow-Origin: *');

At the top of the template

8
  • That is, of course, very sensible. I was stuck in .htaccess thinking.
    – Tim
    Feb 14, 2013 at 19:13
  • This works — but not once the template has been cached. The PHP header isn't being sent again. Any thoughts on how to overcome that?
    – Tim
    Feb 14, 2013 at 19:25
  • You can either disable caching on the template (not sure what you're using to cache it right now), or have the user append a unix timestamp on their api request, making it always unique? I'm fairly new to EE still -- there may be a better method that's EE specific. Feb 15, 2013 at 14:18
  • 1
    Native caching wasn't sending the headers, but I turned on CE Cache (something I've been meaning to do anyway) and now the headers are being sent correctly.
    – Tim
    Feb 15, 2013 at 16:23
  • @DaveDeHaan I have a similar situation and tried to implement your line, but still getting the same message. XMLHttpRequest cannot load http://www.xxxxxxxxx.com/submissions. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
    – Manatax
    Jan 7, 2014 at 22:08
4

You should be able to do this in htaccess:

<IfModule mod_headers.c>
  SetEnvIf Request_URI "^/index.php/embeddable-content(/.*)?" CORS=TRUE
  Header set Access-Control-Allow-Origin "*" env=CORS
</IfModule>

This'll only set the CORS header when your request matches that URI.

1

If you don't want to enable PHP in your templates you can also use https://github.com/nathanpitman/np_access_control_allow_origin.pi.ee_addon to do this. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.