Codeigniter base url issue with www

2019-09-19 13:38发布

I have declared the base url as $config['base_url'] = 'http://example.com/';.

But the issue is if someone try to access my website with 'http://www.example.com/'; , css/ js functions are not working.

If I change the base url to 'http://www.example.com/' , users cannot access with 'http://example.com/'.

I am using codeigniter 3.0.3 . This is an issue with a website which is already online.

CSS - assets/plugins/bootstrap/css/bootstrap.min.css" />

JS - ">

. btw , ajax request are also failed.When I try to access an ajax function the bellow error showing on console –

XMLHttpRequest cannot load http://www.example.com/Dynamic/home/normal/4. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not allowed access.

css error

Font from origin 'http://www.example.com' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not allowed access.

3条回答
小情绪 Triste *
2楼-- · 2019-09-19 14:08

Change your base url from

$config['base_url'] = 'http://example.com/';

to

$config['base_url'] = 'http://www.example.com/';

Reason:www and non-www website url are considered as different website so it gives the error of

Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin'

Better way is the add code in htaccess to convert non-www to www.

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

Hope this explain the reason of change...

查看更多
欢心
3楼-- · 2019-09-19 14:23

Define baseUrl like this

$config['base_url'] = 'stackoverflow.com/';

and .htaccess should be

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

As well as make sure URL helper is loaded.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-09-19 14:27

I think the following code-block shows the best way to configure the base_url in Codeigniter :

$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);

And I strongly believe that this will solve your problem. Thank you.

查看更多
登录 后发表回答