Redirect loop in CI after installing SSL Certificate - apache

I just installed ssl certificate on my site to change the URL from http:// to https:// Everything is complete and i also added a code in my httpd.conf file to automatically add https :// to the UR So the connection is always secure.
However I am facing a problem when i try to login into the Admin Panel. It Goes in a redirect Loop and the webpage gives me a "This webpage has a redirect loop" Error.
https://mysite.com Loads fine but https:/mysite.com/admin goes into a redirect loop.
site is built up using codeigniter Framework for php.
Please Help.
I added this code to my httpd.conf file
#
# Redirect http Request to https
# The lines below are used to redirect http request to https
#
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</IfModule>

Open config file from location application/config/config.php and enable or set hooks to true like this:
$config['enable_hooks'] = TRUE;
Then create a new file named hooks.php inside the config folder (i.e. application/config/hooks.php) and add the following code in it:
$hook['post_controller_constructor'][] = array(
'function' => 'redirect_ssl',
'filename' => 'ssl.php',
'filepath' => 'hooks'
);
Now create a new directory named hooks inside the application folder (i.e. application/hooks) and then create a new file named ssl.php inside the hooks folder (i.e. application/hooks/ssl.php).
Add the following code in the ssl.php file:
function redirect_ssl() {
$CI =& get_instance();
$class = $CI->router->fetch_class();
$exclude = array('client'); // 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());
}
}

Related

Redirect, Hide Folder Name and enabling URL access with multiple subdirectory [duplicate]

I have a URL that looks like:
url.com/picture.php?id=51
How would I go about converting that URL to:
picture.php/Some-text-goes-here/51
I think WordPress does the same.
How do I go about making friendly URLs in PHP?
You can essentially do this 2 ways:
The .htaccess route with mod_rewrite
Add a file called .htaccess in your root folder, and add something like this:
RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /picture.php?id=$1
This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want, without the end user seeing it. Easy, but inflexible, so if you need more power:
The PHP route
Put the following in your .htaccess instead: (note the leading slash)
FallbackResource /index.php
This will tell it to run your index.php for all files it cannot normally find in your site. In there you can then for example:
$path = ltrim($_SERVER['REQUEST_URI'], '/'); // Trim leading slash(es)
$elements = explode('/', $path); // Split path on slashes
if(empty($elements[0])) { // No path elements means home
ShowHomepage();
} else switch(array_shift($elements)) // Pop off first item and switch
{
case 'Some-text-goes-here':
ShowPicture($elements); // passes rest of parameters to internal function
break;
case 'more':
...
default:
header('HTTP/1.1 404 Not Found');
Show404Error();
}
This is how big sites and CMS-systems do it, because it allows far more flexibility in parsing URLs, config and database dependent URLs etc. For sporadic usage the hardcoded rewrite rules in .htaccess will do fine though.
If you only want to change the route for picture.php then adding rewrite rule in .htaccess will serve your needs, but, if you want the URL rewriting as in Wordpress then PHP is the way. Here is simple example to begin with.
Folder structure
There are two files that are needed in the root folder, .htaccess and index.php, and it would be good to place the rest of the .php files in separate folder, like inc/.
root/
inc/
.htaccess
index.php
.htaccess
RewriteEngine On
RewriteRule ^inc/.*$ index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
This file has four directives:
RewriteEngine - enable the rewriting engine
RewriteRule - deny access to all files in inc/ folder, redirect any call to that folder to index.php
RewriteCond - allow direct access to all other files ( like images, css or scripts )
RewriteRule - redirect anything else to index.php
index.php
Because everything is now redirected to index.php, there will be determined if the url is correct, all parameters are present, and if the type of parameters are correct.
To test the url we need to have a set of rules, and the best tool for that is a regular expression. By using regular expressions we will kill two flies with one blow. Url, to pass this test must have all the required parameters that are tested on allowed characters. Here are some examples of rules.
$rules = array(
'picture' => "/picture/(?'text'[^/]+)/(?'id'\d+)", // '/picture/some-text/51'
'album' => "/album/(?'album'[\w\-]+)", // '/album/album-slug'
'category' => "/category/(?'category'[\w\-]+)", // '/category/category-slug'
'page' => "/page/(?'page'about|contact)", // '/page/about', '/page/contact'
'post' => "/(?'post'[\w\-]+)", // '/post-slug'
'home' => "/" // '/'
);
Next is to prepare the request uri.
$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );
Now that we have the request uri, the final step is to test uri on regular expression rules.
foreach ( $rules as $action => $rule ) {
if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
/* now you know the action and parameters so you can
* include appropriate template file ( or proceed in some other way )
*/
}
}
Successful match will, since we use named subpatterns in regex, fill the $params array almost the same as PHP fills the $_GET array. However, when using a dynamic url, $_GET array is populated without any checks of the parameters.
/picture/some+text/51
Array
(
[0] => /picture/some text/51
[text] => some text
[1] => some text
[id] => 51
[2] => 51
)
picture.php?text=some+text&id=51
Array
(
[text] => some text
[id] => 51
)
These few lines of code and a basic knowing of regular expressions is enough to start building a solid routing system.
Complete source
define( 'INCLUDE_DIR', dirname( __FILE__ ) . '/inc/' );
$rules = array(
'picture' => "/picture/(?'text'[^/]+)/(?'id'\d+)", // '/picture/some-text/51'
'album' => "/album/(?'album'[\w\-]+)", // '/album/album-slug'
'category' => "/category/(?'category'[\w\-]+)", // '/category/category-slug'
'page' => "/page/(?'page'about|contact)", // '/page/about', '/page/contact'
'post' => "/(?'post'[\w\-]+)", // '/post-slug'
'home' => "/" // '/'
);
$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );
foreach ( $rules as $action => $rule ) {
if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
/* now you know the action and parameters so you can
* include appropriate template file ( or proceed in some other way )
*/
include( INCLUDE_DIR . $action . '.php' );
// exit to avoid the 404 message
exit();
}
}
// nothing is found so handle the 404 error
include( INCLUDE_DIR . '404.php' );
this is an .htaccess file that forward almost all to index.php
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_URI} !-l
RewriteCond %{REQUEST_FILENAME} !\.(ico|css|png|jpg|gif|js)$ [NC]
# otherwise forward it to index.php
RewriteRule . index.php
then is up to you parse $_SERVER["REQUEST_URI"] and route to picture.php or whatever
PHP is not what you are looking for, check out mod_rewrite
Although already answered, and author's intent is to create a front controller type app but I am posting literal rule for problem asked. if someone having the problem for same.
RewriteEngine On
RewriteRule ^([^/]+)/([^/]+)/([\d]+)$ $1?id=$3 [L]
Above should work for url picture.php/Some-text-goes-here/51. without using a index.php as a redirect app.

OpenWRT HTTPS/SSL Traffic Redirect

I have the following problem:
I'm running a router with openwrt and a lighttpd webserver and i'm trying to redirect https traffic to a specific domain.
Here is my lighttpd.conf:
$SERVER["socket"] == ":443" {
url.redirect = (
"" => "http://name.tld",
)
}
If I call routerip:443 everything works fine,
but when I call https://routerip it gives me an error, for example:
ERR_NETWORK_CHANGED
or something with DNS_ERROR
I suspect it is relying explicitly on the redirect destination, which in your example still uses "http" as the protocol. Try modifying your redirect to include https:
url.redirect = (
"" => "https://name.tld",
)

301 redirect for old Ajax permalinks

My clients old site was running through Wix.
Wix creates AJAX permalinks like this: old-domain.com/#!about/c20r9 instead of this: old-domain.com/about
I have developed a new WordPress site for them via new-domain.com. old-domain.com has been added to new-domain.com as a domain alias.
I would like to re-direct old page urls from old-domain.com to specific pages on new-domain.com. For example: old-domain.com/#!about/c20r9 should re-direct to: new-domain.com/about.
I understand that 301 redirect rules do not work as the server will not recognise hash urls.
How can I re-direct the old URLs for old-domain.com to new-domain.com?
As mentioned in my comment, JavaScript is the way to go as the fragment (#...) is never sent to the server.
In your specific case, you could use the following JS code to redirect your page accordingly.
Automatic mode: Use if the page names have not changed:
// Get the current hash
var currentHash = window.location.hash;
// If there is one, and it is in fact a hashbang, redirect it to the new URI.
// This extracts the 'about' from '#!about/c20r9', for example, and assigns the
// location (/about) once extracted.
if (currentHash.indexOf('#!') == 0){
window.location.assign(currentHash.replace(/^#!([^\/]+)\/.*/, '$1'));
}
Manual mode: Use if your page names differ (when comparing Wix to your migrated site). This method maps the redirects using an object, scans the object, and redirects if a match is found.
// Get the current hash
var currentHash = window.location.hash;
// If there is one, and it is in fact a hashbang, redirect it to the new URI,
// based on the array set out.
if (currentHash.indexOf('#!') == 0) {
// Get the old page name from the hash
var oldPageHash = currentHash.replace(/^#!([^\/]+)\/.*/, '$1');
// Define the redirects (old and new counterparts)
var redirects = {
'foo-page': 'new-foo-page',
'bar-page': 'new-bar-page',
}
// Loop through the redirects and set the location if there is a match
for (var oldPage in redirects) {
if (redirects.hasOwnProperty(oldPage)) {
if (oldPage == oldPageHash) {
window.location.assign(redirects[oldPage]);
}
}
}
}

Redirecting to relative path using Laravel 4

Is it possible, in Laravel 4.1, to redirect to a relative path instead of the full path ? If we look at the UrlGenerator::to method, here what we have:
public function to($path, $extra = array(), $secure = null)
{
if ($this->isValidUrl($path)) {
return $path;
}
$scheme = $this->getScheme($secure);
$tail = implode('/', array_map('rawurlencode', (array) $extra));
$root = $this->getRootUrl($scheme);
return $this->trimUrl($root, $path, $tail);
}
This will act like this (meta-code):
mysite.com/url Redirect::to('/test'); => mysite.com/test
What I'd want it's to be redirected to a relative URL:
mysite.com/url Redirect::to('/test'); => /test
The problem it's that the company I'm working for, use a ReverseProxy to redirect all the traffic to HTTPS protocol, and with this kind of laravel redirects I keep getting redirected from HTTP to HTTPS :
call: GET http:// mysite.com
proxy: GET https:// mysite.com
redirect to login: GET http:// mysite.com / login
proxy: GET https:// mysite.com / login
submit login: POST http:// mysite.com / login
proxy: POST https:// mysite.com / login
And the problem is that the submit form fail.
Is there a possibility to redirect to the relative path and let the proxy define the root url / protocol to use ?
I'm on Laravel 4.2, I'm using Redirect::away('/test'), not sure if the function is there yet on Laravel 4.1.

Recursively look in subdirectories for matching filename.

if a file is not found, i would like to recursively check in subdirectories until a file with the requested name is found and deliver that.
example:
the request is:
http://domain.com/file.txt
look recursively in subdirectories until file.txt is found, then deliver:
http://domain.com/foo/bar/file.txt
the only thing i have managed so far is the trigger when a file is not found:
RewriteCond %{REQUEST_FILENAME} !-f
Take this into a loader script. First, have this rewrite in your application (vhost configuration or .htaccess file)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /loader.php?q=$1 [L,QSA]
Then have a loader.php script in the root directory of your website, that would search for a file recursively and either redirect to the proper URL or load the file, get the mime tipe, set the proper headers and respond with the content of that file. Something like this:
<?php
// Do some processing here to extract the proper file name
// from $_REQUEST['q'] into a variable called $filename
// Assume we have the $filename
$it = new RecursiveDirectoryIterator(__DIR__); // Start search where loader.php is located
foreach (new RecursiveIteratorIterator($it) as $file) {
if (pathinfo($file, PATHINFO_BASENAME) == $filename) {
$returnFile = $file;
break;
}
}
// Check if the file was found
// Do a proper redirect to the 404 page here if you need more
if (empty($returnFile)) {
header ("HTTP/1.0 404 Not Found");
die();
}
// You need to do some fancy magic here to set the proper content type
// We will return plain text for now
header("Content-Type:text/plain");
// Handle large files
set_time_limit(0);
$file = #fopen($file_path,"rb");
while(!feof($file))
{
print(#fread($file, 1024*8));
ob_flush();
flush();
}
/* EndOfScript */
And that's about it, I guess... I haven't tested this AT ALL, so there might be a lot wrong with it! Then again, you can get the main picture of how you can handle this issue!