简体   繁体   中英

Access-Control-Allow-Origin and www subdomain

I am having troubles with Access-Control-Allow-Origin. I am using CodeIgniter (CI) & jQuery to make a jQuery.getJSON() call. I call jQuery.getJSON() using a CI URL. My base URL in the CI config includes the www (www.domain.com) in the domain name. When I am accessing the site, I am not using www (domain.com). So when the jQuery.getJSON() call is made it uses the www url, but it is being called from the non-www url. This is causing the error:

Origin non-www.domain.com is not allowed by Access-Control-Allow-Origin.

How do you deal with this problem? I have seen lots of posts about how to deal with different sub domains making these AJAX calls, but I feel like this is different. This is the same site, but some people may choose to use www.domain.com and some may choose to use just domain.com .

I would suggest you pick once and for all whether or not you want www in front of your site and then setup apache redirect accordingly, which would save you a lot of headache:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain\.com
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=permanent,L] 

(this redirects non-www requests to www)

Thanks @serg. I ended up doing what you suggested, but just the inverse (redirected all www to non-www). I also found similar code to what you provided but it is more generic so I don't have to change the domain name when I want to reuse it:

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM