Codeigniter 2.x SSL Redirect Loop - php

I'm working on a pre-existing codeigniter (v2.1.4) application to add https/ssl to it.
I'm working in webfaction hosting. Their normal method of ssl setup includes adding a second website record in the host dashboard which redirects http:// to https:// using the .htaccess (let's call this .htaccess_B for clarity's sake) file. This website record only contains this .htaccess file:
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-SSL} !on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
The original website record which contains the CodeIgniter application contains this .htaccess (.htaccess_A) file
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|javascript|images|robots\.txt)
RewriteRule ^(.*)$ /index.php?/$1 [L]
The SSL certificate is installed and configured correctly as per the webhost instructions. I have tried this method (top answer) but I'm stuck in a redirect loop.
My config variables in config.php:
$config['base_url'] = '';
$config['enable_hooks'] = TRUE;
$config['cookie_secure'] = TRUE;
hooks.php
$hook['post_controller_constructor'][] = array(
'function' => 'redirect_ssl',
'filename' => 'ssl.php',
'filepath' => 'hooks'
);
and my ssl.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function redirect_ssl() {
$CI =& get_instance();
$class = $CI->router->fetch_class();
$exclude = array(''); // add more controller name to exclude ssl.
if(!in_array($class,$exclude)) {
// redirecting to ssl.
$CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] != 443) redirect($CI->uri->uri_string());
} else {
// redirecting with no ssl.
$CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] == 443) redirect($CI->uri->uri_string());
}
}
`
I've tried several things including renaming the .htaccess file on the original website record (.htaccess_A), adding a base_url with https:// to no avail. I keep getting stuck in a redirect loop
GET https://mydomainhere.com/ net::ERR_TOO_MANY_REDIRECTS in chrome
console
Any ideas?
Thanks

Change base_url in your config:
$config['base_url'] = 'https://mydomainhere.com/';
Redirect incoming traffic from http to https:
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Related

Only default controller is working and the rest is 404 not found

I'm using codeigniter on my wamp and everything is fine but when I upload it on live server the default_controller is working but the other controller are 404 not found or "The requested URL /Sample_controller was not found on this server".
Here is my sample controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Sample_controller extends CI_Controller {
function __construct(){
parent::__construct();
}
public function index(){
print_r('Hello World');
}
}
and here's my config.php:
$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/';
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
$config['allow_get_array'] = TRUE;
and this is my router.php:
$route['default_controller'] = 'login';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
and my .htaccess:
<IfModule mod_rewrite.c>
Options +FollowSymLinks
Options +Indexes
RewriteEngine On
RewriteBase /folder
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} !www.sampleurl.com$ [NC]
RewriteCond %{REQUEST_URI} ^/$
RewriteCond $1 !^(index\.php|assets|user_assets|tmp|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>
if I tried this sampleurl.com it's working fine and will direct me to my default controller which is the login but if i tried this sampleurl.com/sample_controller or sampleurl.com/login it will lead me to 404 not found The requested URL /sample_controller was not found on this server. Apache/2.4.7 (Ubuntu) Server at sampleurl.com Port 80
I hope someone can help me on this
I tried changing them to:
$config['uri_protocol'] = AUTO
$config['enable_query_strings'] = TRUE;
and it's still not working.
You need to add a route for that controller to work
$route['sample_controller'] = 'sample_controller';
For every new controller you create you need to have a route for it
According to your code, you may have these 2 issues:
1- As per documentation you are required to make your controller filename first character Uppercase.
2- Try adding a question mark "?" in your .htaccess file's last rule. Also remove the "/" before "index.php" check the code below.
Current code:
RewriteRule ^(.*)$ /index.php/$1 [L]
New code:
RewriteRule ^(.*)$ index.php?/$1 [L]
Just simply change
RewriteBase /folder
This line of code in your .htaccess file to appropriate folder name of your project and it will work fine.

How to configure Codeigniter for HTTPS (SSL)?

I have a Codeigniter application which was developed and tested on the normal http. Now the Apache server has been configured in such a way that all of the pages are stored in a single folder which is SSL enabled. The SSL certificate is in place. When I browse to the website using "https://www" then it redirects to "http://www".
NOTE : I do not need to load specific pages using SSL. I just need all pages to show as HTTPS.
I have tried the proposed solutions suggested on Stack Overflow including :
Modifying the .htaccess file to force HTTPS
Setting the $config['base_url'] = "https://www.yoursite.com/";
When I tried the above method in tandem then Firefox gave the following error :
The page isn't redirecting properly. Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
Many Stack Overflow contributors suggest that this should be handled by Apache only. That makes sense to me but forcing HTTPS via .htaccess gives the same error.
Is there a simple way to do this without hooks and SSL Helpers, etc?
This answer is a bit (read: a lot) late, but you can use this hook I made (5 minutes ago), It'll redirect to your HTTPS website and set some headers.
I use it along with this .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?/$1 [L]
It is easy,
Go to applicaton/config.php and insert the following code:
$base = "https://".$_SERVER['HTTP_HOST']; // (For https)
See line 19 on image.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$base = "https://".$_SERVER['HTTP_HOST']; // HERE THE CORRECT CODE
$base .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url'] = $base;
Step 1
Setting the $config['base_url'] = "https://www.yoursite.com/";
Step 2
Use and edit this .htaccess file.
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
Step 1: application/hooks/ssl.php
function force_ssl()
{
$CI =& get_instance();
$CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] != 443) redirect($CI->uri->uri_string());
}
Step 2: application/configs/hooks.php
$hook['post_controller_constructor'][] = array(
'function' => 'force_ssl',
'filename' => 'ssl.php',
'filepath' => 'hooks'
);
Step 3:application/config/config.php
$config['enable_hooks'] = TRUE;
htaccess Changes :
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R,L]
'mod_rewrite' module to be installed on your Apache server
Final: restart Apache server.
CI_app\application\config\config.php
$base_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$base_url .= "://". #$_SERVER['HTTP_HOST'];
$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url'] = $base_url;
.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
# Require HTTPS
RewriteCond %{HTTPS} !=on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
# Removing the index.php file - https://codeigniter.com/userguide3
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Codeigniter return 404 page not found

I'm developing web application using Codeigniter. So far I have managed to run the application on my localhost. But when I upload the content unto the web hosting, I can't get it to run.
This is what I've tested so far:
strangely, I can call the controller Welcome.php which is the sample controller from codeigniter, and showing well.
But I can't call any other controller which my default controller eventhough I have set it in routes.php, config.php etc.
Below is my configuration for these files:
routes.php
$route['default_controller'] = 'lokadok';
$route['404_override'] = '';
$route['upload/do_upload'] = 'upload/do_upload';
config.php
$config['base_url'] = (( isset($_SERVER['HTTP_HOST']) && strlen($_SERVER['HTTP_HOST'])>0) ?
'http://' . $_SERVER['HTTP_HOST'] : 'http://www.lokadok.co.id' );
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';
$config['url_suffix'] = '.html';
$config['charset'] = 'UTF-8';
and this is the .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^(/index\.php|/assets|/robots\.txt|/favicon\.ico)
RewriteRule ^(.*)\.html$ /index.php/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^(/index\.php|/assets|/robots\.txt|/favicon\.ico)
RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
ErrorDocument 404 /index.php
</IfModule>
My default controller is this:
lokadok.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Lokadok extends CI_Controller {
public function index() {
$data['is_login'] = $this->session->userdata(LOGGED_IN);
$specialty = $this->input->post('specialty', '');
$address = $this->input->post('address', '');
$doc_name = $this->input->post('doc_name', '');
if ($specialty == '' && $address == '' && $doc_name == '') {
$this->load->model('model_share');
$data['custom_css'] = array(
'style/custom/lokadok.css'
);
$data['sort_by'] = 1;
$data['pop_specialties'] = $this->model_share->get_specialties(true);
$data['specialties'] = $this->model_share->get_specialties();
$this->load->view('templates/header', $data);
$this->load->view('lokadok_view');
$this->load->view('templates/footer', $data);
} else {
redirect("search?specialty=$specialty&address=$address&doc_name=$doc_name&sort_by=1");
}
}
}
?>
I have been looking for the answer for awhile and still couldn't figure it out. So if anyone can spot the error, I would really appreciate it.
To check on the location site you can go to:
www.lokadok.co.id which I expect to call my default controller.
and try to call http://www.lokadok.co.id/welcome which is strangely running well.
Thank you all, and hope my explanation is clear.
I think the answer lies within your question :
<IfModule !mod_rewrite.c>
ErrorDocument 404 /index.php
</IfModule>
I think you need to enable mod_rewrite
UPDATED
Find your php.ini in
/etc/php.ini
Or here:
/etc/php/php.ini
/etc/php5/php.ini
Find the line with disable_functions, one of them likely being phpinfo. You'll need to remove phpinfo from the list of disabled functions in disabled_functions=
IF UBUNTU THEN
To enable the rewrite module, run "apache2 enable module rewrite" in terminal:
sudo a2enmod rewrite
You need to restart the webserver to apply the changes:
sudo service apache2 restart

Rewrite URL with .htaccess and HTTPS

I have a web site where I have to use a .htaccess file to redirect all requests to index.php, where redirecting is handled.
I want to rewrite the URL, and at the same time use HTTPS. Without HTTPS it works fine.
Code from working .htaccess without HTTPS. Browser gets this input: alert/create
RewriteRule ^([a-zA-Z]*)/?([a-zA-Z]*)?/?([a-zA-Z0-9]*)?/?$ index.php?controller=$1&action=$2&id=$3 [NC,L]
This works fine, but without HTTPS. Browser URL becomes http://localhost/mypage/alert/create, and that's what I want.
I found a solution that allows me to use HTTPS:
RewriteRule ^([a-zA-Z]*)/?([a-zA-Z]*)?/?([a-zA-Z0-9]*)?/?$ https://%{SERVER_NAME}/mypage/index.php?controller=$1&action=$2&id=$3 [NC,L]
Page navigation works like a charm, but browser displays the URL like this:
https://localhost/mypage/index.php?controller=alert&action=create&id=
Requests are handled like this:
public function __construct($urlvalues) {
$this->urlvalues = $urlvalues;
if ($this->urlvalues['controller'] == "") {
$this->controller = "home";
} else {
$this->controller = $this->urlvalues['controller'];
}
if ($this->urlvalues['action'] == "") {
$this->action = "index";
} else {
$this->action = $this->urlvalues['action'];
}
}
I need some hints. I've been looking all over internet without solving my problem...
If I can use .htaccess, but implement HTTPS another way, that'll be perfect too.
Server code written in PHP, running on apache2.
I would have done this in two steps. The first that you already have. And this one :
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L]
Solved! Solution: Added this to .htaccess, in that order spesifically:
RewriteEngine on
#force https
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteRule ^([a-zA-Z]*)/?([a-zA-Z]*)?/?([a-zA-Z0-9]*)?/?$ index.php?controller=$1&action=$2&id=$3 [NC,L]

.htaccess multiple-domain rewrite

I'm looking for a solution to support multiple domains on one webhosting account, which has to be done with htaccess. So the idea is, you call domainx and with htaccess the server "fakes" the webroot to a subfolder corresponding with the domain name. I allready have a "solution", but this doesn't work perfectly.
Problems I've got:
Redirects through PHP (with base_url() of CodeIginiter), result in; for example "http://www.domein1.nl/domein1.nl/".
It doesn't work on my local server.
So, the htaccess I'm currently using:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} domein1.nl$ [NC]
RewriteCond %{REQUEST_URI} !^/domein1.nl/.*$
RewriteRule ^(.*)$ /domein1.nl/$1 [L]
RewriteCond %{HTTP_HOST} domein2.nl$ [NC]
RewriteCond %{REQUEST_URI} !^/domein2.nl/.*$
RewriteRule ^(.*)$ /domein2.nl/$1 [L]
</IfModule>
The CodeIgniter PHP-code for the base_url(). The server variable "SCRIPT_NAME" adds the second domain folder, marked as problem 1. This should'nt happen if the root folder is faked correctly; but is that actually possible?
if (isset($_SERVER['HTTP_HOST']))
{
$base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
$base_url .= '://'. $_SERVER['HTTP_HOST'];
$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
}
And last but not least, it is'nt working on my local server while I do redirect through my hosts file:
192.168.2.9 local.domein1.nl
192.168.2.9 local.domein2.nl
Sooo.. How do I fix these problems? Thanks in advance!
Edit: The problem with my local server is fixed.. cough "sudo a2enmod rewrite" did the trick..
Edit2: Since stormdrain started about folder structure, here is mine to clarify the multiple CI applications.
Main .htaccess location / webroot
/public_html/.htaccess
domain1:
/application/domain1/ (domain1 application path)
/application/system/ (shared system path)
/public_html/domain1/index.php (CI domain1 index)
domain2:
/application/domain2/ (domain2 application path)
/application/system/ (shared system path)
/public_html/domain2/index.php (CI domain2 index)
It's not totally clear what you are trying to do. Sounds like you have several domain names pointing to the same server in which you don't have full control and therefore can't set up VirtualHosts. You also want to serve the domains with a single application and not have a subfolder as part of the URL (e.g. you don't want http://www.domain1.nl/domain1.nl as the URL's home page).
If so, this might work:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} domein1.nl$ [NC]
RewriteRule ^(.*)$ /domein1/$1 [L]
RewriteCond %{HTTP_HOST} domein2.nl$ [NC]
RewriteRule ^(.*)$ /domein2/$1 [L]
</IfModule>
Then create routes in CodeIgniter to route the request:
$route["/domein2/(:any)"] = "/domein2/$1";
To get the rewrites working locally, you need to add the domain to the .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} local.domein1.nl$ [NC]
RewriteRule ^(.*)$ /domein1/$1 [L]
RewriteCond %{HTTP_HOST} local.domein2.nl$ [NC]
RewriteRule ^(.*)$ /domein2/$1 [L]
</IfModule>
Then base_url shouldn't need the SCRIPT_NAME since it is being rewritten and routed out of the URL:
if (isset($_SERVER['HTTP_HOST']))
{
$base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
$base_url .= '://'. $_SERVER['HTTP_HOST']. '/';
}
Update.
If you have a CI folder for each domain like:
/var/www/domain1/index.php
/var/www/domain1/application/
/var/www/domain1/system/
etc.
/var/www/domain2/index.php
/var/www/domain2/application/
/var/www/domain2/system/
etc.
RewriteCond %{HTTP_HOST} domain1.nl$ [NC]
RewriteRule ^(.*)$ /domain1/$1 [L]
RewriteCond %{HTTP_HOST} domain2.nl$ [NC]
RewriteRule ^(.*)$ /domain2/$1 [L]
Should do the job for you.
Well, it seems impossible to do neatly through htaccess..
O well, I "fixed" it. My fix within the CodeIgniter index.php: I replaced the declaration of the variable $application_folder with the code beneath.
define('DOMAIN', preg_replace(
"/^(www.|local.)?([^.]+).[^.]+$/i", "\\2",
$_SERVER['HTTP_HOST']
));
if ( DOMAIN == 'domain2')
$application_folder = '../application/domain2';
else
$application_folder = '../application/domain1';
I also made a minor change to the system "url_helper". Added this "static_url()" function, returning the URI to the path I save images/CSS/js etc.
if ( ! function_exists('static_url'))
{
function static_url()
{
return base_url().'static/'.DOMAIN.'/';
}
}
Only minor thing I've got to figure out is how to split up things like robots.txt

Categories