Wildcard subdomains with .htaccess (Codeigniter) - .htaccess

In my current project, I was asked to provide blog feature for every registered user, that means when you register, you can automatically write blogs on site. This was easily done, however, I was instructed to use URLs in format like http://username.site.com refering with username to specific user blog.
I am trying to achieve this with .htaccess file, but it seems my conditions are met but I am getting 500 Internal Server Error, wich is caused by infinite loop of rewrites. I would like to avoid that but I can't find suitable solution. Here is my .htaccess so far:
<IfModule mod_rewrite.c>
Options +FollowSymLinks
Options +Indexes
RewriteEngine On
RewriteBase /
RewriteCond $1 !^(index\.php|images|tinymce|files|css|js|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteCond %{HTTP_HOST} ^(www.)?([a-z0-9-_]+).dev.example.com [NC]
RewriteRule ^(.*)$ /index.php/blog/%2/$1 [L]
</IfModule>
Additional info: The site is server hosted, but hidden and on dev.example.com so blog URL's should look like username.dev.example.com, when site will be launched, this will of course be username.example.com. It's built with Codeigniter.
Any suggestions about improving that .htaccess would be great, thank you.

The best way to do this is not using .htaccess.
This is what I would do:
Create a wildcard DNS record *.example.com
Create a blog modal, pick up $_SERVER['HTTP_HOST'], explode it and remove your domain. Do the lookup in your DB table.
EDIT:
Create a wildcard DNS record, lets say create an CNAME *.example.com > www.example.com
This way, when I goto kyle.example.com its really loading www.example.com.
Create a blog model:
row_count() > 0) {
$blogInfo = [
'blog_id'=>123, // value from db
'blog_name'=>'Kyles Test Blog',
...
];
$this->session->set_userdata($blogInfo);
return $blogInfo;
} else {
return false;
}
}
}
?>
// controller
session->userdata('blog_id')) { // blog id not saved session
$this->load->model('blog_model'); // load the blog model
$url = str_replace('.example.com', '', strtolower($_SERVER['HTTP_HOST'])); // get the current hostname, eg kyle.example.com
if($url !== 'www') {
if($blog_info = $this->blog_model->checkForValidBlog()) {
// load your blog
redirect('/blog/' . $blog_info['blog_id'] . '/');
} else {
show_error('Error - Blog not found', 404);
}
}
} else {
// load your blog
redirect('/blog/' . $blog_info['blog_id'] . '/');
}
}
}
?>

Related

Codeigniter redirect issue with https

I'm adding a pdf function to my project, but I have a strange issue with redirecting the function after it is completed.
initially, it works well on localhost and on a test host not using ssl certificate, but it is not working on the domain associated with ssl certificate I don't know the reason and no debugging info can guide me when I should start.
The working code with no ssl : http://idev-inc.com/lab/rwahl.com/invoice
You have to book hotel to get the link works with you otherwise it will rediect you to the homepage.
The same function and repo at this url : https://rwahl.com/ndmilestone/invoice
I looked for the most threads about redirection with ssl and I updated the
.htaccessto the following :
RewriteEngine on
# Enforce SSL https://www.
RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
###
# Removes access to the system folder by users.
# Additionally this will allow you to create a System.php controller,
# previously this would not have been possible.
# 'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php/$1 [L]
# Checks to see if the user is attempting to access a valid file,
# such as an image or css document, if this isn't true it sends the
# request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#####RewriteRule ^(.*)$ /ndmilestone/index.php/$1 [L]
RewriteRule ^(.*)$ /ndmilestone/index.php?/$1 [L,QSA]
I'm using mpdf library to generate the pdf files , And this is the invoice_as_pdf function :
function invoice_as_pdf(){
$assumptiondata=Array();
$filename="invoice".time().rand(1,9);
// As PDF creation takes a bit of memory, we're saving the created file in
// /downloads/reports/
$sub_folder="downloads/reports/$filename.pdf";
$pdfFilePath = FCPATH."/".$sub_folder;
$finalurl=base_url().$sub_folder;
// pass data to the view
if (file_exists($pdfFilePath) == FALSE){
ini_set('memory_limit','32M'); // boost the memory limit if it's low ;)
$this->theme->view('Admin/modules/global/invoice', $this->data, $this);
$html = $this->load->view('Admin/modules/global/idev_invoice_print', $data, true); // render the view into HTML
$this->load->library('pdf');
$mpdf = $this->pdf->load();
$mpdf=new mPDF('utf-8');
// $pdf->useAdobeCJK = true;
$mpdf->charset_in='UTF-8';
// Add a footer for good measure ;)
$mpdf->SetFooter($_SERVER['HTTP_HOST'].'|{PAGENO}|'.date(DATE_RFC822));
$mpdf->SetDirectionality('rtl');
$mpdf=new mPDF('ar','A4','','',32,25,27,25,16,13);
$mpdf->SetDirectionality('rtl');
$mpdf->mirrorMargins = true;
$mpdf->WriteHTML($html); // write the HTML into the PDF
$mpdf->Output($pdfFilePath, 'F'); // save to file because we can
}
$this->load->helper('url'); // it is auto-loaded but I'm testing to call here also
redirect($finalurl); //redirect to the new PDF
}
The pdf files are generated successfully also, actually I tried several scenarios but till now I couldn't get the reason for that.
Thanks in advance.

server error 500, while entering wrong address in Laravel 5

I have a Laravel 5.0 project. When I enter wrong link on locahost, Laravel redirects me to custom error template, using this code on app\Exceptions\Handler.php.
protected $dontReport = [
HttpException::class,
ModelNotFoundException::class,
];
public function render($request, Exception $e)
{
if($this->isHttpException($e)){
switch ($e->getStatusCode()) {
case '404':
\Log::error($e);
return \Response::view('error');
break;
case '500':
\Log::error($exception);
return \Response::view('error');
break;
default:
return $this->renderHttpException($e);
break;
}
}
else
{
return parent::render($request, $e);
}
}
After moving my laravel project to shared Hosting (not Linux) site does not redirect me to custom error template (views/error.blade.php), while entering wrong address which does not exist in app/http/routes.php. I tried many solutions, configured .htaccess file, but did not get a result. Error.log is empty. Here is my .htaccess file:
AddHandler application/x-httpd-php54 .php
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
I also tried remove RewriteCond and RewriteRule lines. In this case I can get 404 error page, but it brings me problems:
1) Laravel will not recognize aliases, if exists. For example (www.site.com/news)
2) Laravel will not send post requests to another page, for example (www.site.com/post)
3) Laravel will not display custom error template (views/error.blade.php) if I type wrong address, which not exists in app/http/routes.php, For example (www.site.com/wrong)
For accessing site without public, I made some changes:
1) I moved all files from public_html, except public folder to applicaton folder. Then, moved files from public folder into public_html.
2) Little changes in index.php
before:
require __DIR__.'/../bootstrap/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';
after:
require __DIR__.'/application/bootstrap/autoload.php';
$app = require_once __DIR__.'/application/bootstrap/app.php';
My files structure in public_html:
application
app (inside application folder)
server.php (inside application folder)
.htaccess
index.php
I accidentally replaced laravel 5.0 handler.php to laravel 5.1 handler.php.
I edited protected $dontReport file.
before
protected $dontReport = [
HttpException::class,
ModelNotFoundException::class,
];
after
protected $dontReport = [
'Symfony\Component\HttpKernel\Exception\HttpException'
];

Usernames as subdomain

I have a multi-user website which generates user profiles.
By default, the profiles as set to the users' id, e.g. mysite.com/userid
I'd like to be able to change that to the username instead, and place it on the subdomain, e.g. username.mysite.com
Both the id and username are unique in mysql so there will be no duplicate issues.
But I'm struggling to find a way to do this.
I consulted this article: How to let PHP to create subdomain automatically for each user?
Which gave me some idea on how to start, but technically I'm lost.
I added the subdomain *.mysite.com, and tried the following in my .htaccess file:
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([^a-zA-Z0-9-]*)$ profile/?id=$1
RewriteCond %{HTTP_HOST} ^(^.*)\.mysite.com
RewriteRule (.*) profile/?id=%1
Where "mysite.com" is my actual site. But it produced 404 errors.
Inside my index.php is the following line for seo profile pages:
$router->map(get_option('profile-seo-url','/profile/:name/:id/:section'), 'profile', array('methods' => 'GET,PUT,POST', 'filters' => array('id' => '(\d+)','section' => '(.*)')));
Is this overriding the htaccess file?

Subdomain vanity username rewrite

I'm curious as to how Tumblr's vanity sub-domain works.
I'm not sure if its through an htaccess redirect but how would you rewrite:
myname.mywebsite.com
To:
www.mywebsite.com/profile.php?username=myname
Any pointers is deeply appreciated.
You don't necessarily need to rewrite anything. You can configure a web application instance or website (in IIS, Apache, etc) to respond to all requests, regardless of Host header (i.e. the domain name). The web application can then interrogate the Host header within application code and respond accordingly:
<?php
$domainName = $_SERVER['HTTP_HOST'];
if( $domainName == 'foo.mydomain.com' ) {
// do something special?
} else {
echo $domainName;
}
?>
Also note that the guide on Apache's website ( http://httpd.apache.org/docs/2.0/misc/rewriteguide.html ) states how to perform URI rewriting based on the Host header (see the section on "Virtual User Hosts"):
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.[^.]+\.host\.com$
RewriteRule ^(.+) %{HTTP_HOST}$1 [C]
RewriteRule ^www\.([^.]+)\.host\.com(.*) /home/$1$2

Htaccess alias redirect fake multilanguage url

I have a domain www.domain.com with this kind of url
www.domain.com/my-italian-page.html (already rewritten by others htaccess rules)
I'd like to create a fake multilanguage url like
www.domain.com/my-english-page.html
The user will see in the address bar the rewritter url www.domain.com/my-english-page.html but the content that I'd like to show is the original www.domain.com/my-italian-page.html .
I'm on a shared server so I can't use apache vhost rule so I have to find a solution via htaccess.
Someone could help me to find the right way?
Thanks
So you want english URLs pointing to italian content? Hope your php script that generates these rewrite rules does the translating. But you'd do this for each one of your pages:
RewriteRule ^/?english-page.html$ /italian-page.html [L]
for each one of your pages.
Generally you want to keep the code executed in the web server as small as possible, so having a rewrite rule for each page is not usually a good idea. I suggest to implement this the way most CMS work when SEO URLs are enabled:
Rewrite any url (mydomain/anytext.html [actually you should not use the .html extension either]) to a script (eg. mydomain.tld/translate.php)
Use content of $_SERVER['PATH_INFO'] (should contain anytext.html) to display the correct page
Set correct HTTP response code if page does not exist: http_response_code(...) (see end of this answer for a function on php5 below 5.4: PHP: How to send HTTP response code?)
Sample .htaccess (actually originally "stolen" and severely modified from a typo3 setup)
RewriteEngine On
# Uncomment and modify line below if your script is not in web-root
#RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-s
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule (.*) translate.php$1 [L]
Very basic pseudo-code-like (not tested, there may be syntax errors) example:
<?php
// using a database? you have to escape the string
$db = setup_db();
$page = db->escape_string(basename($_SERVER['PATH_INFO']));
$page = my_translate_query($page);
// no database? do something like this.
$trans = array( 'english' => 'italian', 'italian' => 'italian' );
$page = 'default-name-or-empty-string';
if(isset($_SERVER['PATH_INFO'])) {
if(isset($trans[basename($_SERVER['PATH_INFO'])])) {
$page = $trans[$trans[basename($_SERVER['PATH_INFO'])]];
}
else {
http_response_code(404);
exit();
}
}
// need to redirect to another script? use this (causes reload in browser)
header("Location: otherscript.php/$page");
// you could also include it (no reload), try something like this
$_SERVER['PATH_INFO'] = '/'.$page;
// you *may* have to modify other variables like $_SERVER['PHP_SELF']
// to point to the other script
include('otherscript.php');
?>
I saw in your answer that you have another script - dispatcher.php - which you seem reluctant to modify. I modified my response accordingly, but please keep in mind that by far the easiest way would be to just modify the existing script to handle any English paths itself.

Resources