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).

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

| improve this answer | |
  • That is, of course, very sensible. I was stuck in .htaccess thinking. – Tim Feb 14 '13 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 '13 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. – Dave DeHaan Feb 15 '13 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 '13 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 '14 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.

| improve this answer | |
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. :)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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