server error 500, while entering wrong address in Laravel 5 - .htaccess

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'
];

Related

How to remove public? from url in php project

I am currently working to build a small php mvc framework. in a framework i have a this folder structure.
-app
--controllers
-Post.php
-core
-logs
-public
--.htaccess
-- index.php
-vendor
in here index.php is working as Front Controller
in post controller is look like this..
<?php
/**
* Posts controller
*
*/
class Posts
{
public function index()
{
echo 'Hello index';
}
public function addNew()
{
echo 'Hello addNew';
}
}
in url, i want to remove project/public/?posts/index public/?. When i remove (public/?) and visit the url. its showing me this error message.
project/posts/index
The requested URL was not found on this server.
using public/? project/public/?posts/index is working fine. and its echo index message
project/public/
The .htaccess inside of the public folder contains:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
in project main root folder ...
i did't added .htaccess and index.php file.
in .htaccess when i add this line. url redirect to xammp welcome screen
RewriteRule ^(.*)$ index.php?$1 [L,QSA]
I'd say you want to internally rewrite all incoming requests to the controller inside the /project/public folder. But that is not what you do. The rule you implemented (RewriteRule ^(.*)$ index.php?$1 [L,QSA]) only rewrites relative to the requested folder. No mentioning of "public" in there.
The actual setup you need depends a bit on your http host setup here. Where its DOCUMENT_ROOT points to. Most likely to the folder that contains the file system structure you posted in your question. If so you should implement a rule that rewrites all incoming requests to the /project/public folder.
Something like that, though you probably need to tweak it to match your actual setup:
RewriteEngine on
RewriteRule ^ /public/index.php?%{REQUEST_URI} [L,QSA]
You can implement such rule in the http server's host configuration. Or, if you do not have access to that, you can use a distributed configuration file (if you have enabled those for the http host), so a ".htaccess" style file. That file should be located inside the folder your http hosts DOCUMENT_ROOT setting points to. So the folder containing the file system structure your posted.
Other setups are possible, this is just one option. The point is: you need to rewrite the requests to your controller. Where the controller actually is.

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.

Removing public from laravel 5.2 without changing location of default index.php and htaccess files

I have created an htaacess file as mentioned at below link
icodehub.in
After creating htaccess file and writing below code in it I am able to access my public folder without writing public in url but still framework is not working properly like:
1. when I die a text inside index.php it is showing up on webpage but once the line "$response->send();" execute it error blade starts showing and images and other asset's url looks like this :
http://localhost/common/images/404.jpg
http://localhost/common/images/404.jpg
My .htaccess file outside public which I have created myself:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
The solutions I found on SO and other sites are to place index and htaccess file outside public folder on project root. But I don't want to do that I want to change htaccess only so that I don't have to write public in my urls.
Creating virtual host was also the solution but I also don't want to do that.
Please suggest If anyone know solutions other than creating virtual host or moving files outside public folder.
Already referred below solutions:
Laravel 5 - Remove public from URL
http://icodehub.in/remove-public-from-url-laravel-5/
http://tutsnare.com/remove-public-from-url-laravel/
http://laravel.io/forum/03-11-2014-removing-public-from-url
etc.
Thanks!
Update
After installing a fresh project when I followed same step that is creating htaccess file on project root and writing below code in it I got below error:
htaccess file code:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
error
Sorry, the page you are looking for could not be found.
1/1 NotFoundHttpException in RouteCollection.php line 161:

Wildcard subdomains with .htaccess (Codeigniter)

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'] . '/');
}
}
}
?>

Getting Symfony2 to work on shared hosting using only .htaccess

I've been searching for this for 4 days now and couldn't find a working solution.
I want to make Symfony2 work on shared hosting without access to command line or httpd.conf (there's no way to set virtual host). All I can do, is just edit .htaccess files. In my web root directory I also have some other projects (like forum). The directory structure is:
public_html
|-forum
|-ox
'-Symfony
|-app
|-bin
<...>
I can make it work both in dev ant prod environments (routing works well), BUT it doesn't load any assets (js, css, images). In error log there's always the same:
request.ERROR: Symfony\Component\HttpKernel\Exception\NotFoundHttpException: No route found for "GET /bundles/acmedemo/images/welcome-demo.gif" (uncaught exception)
Same happens if asset is loaded not from bundles, but also in twig as:
{{ asset('css/main.css') }}
Then it ends up with
request.ERROR: Symfony\Component\HttpKernel\Exception\NotFoundHttpException: No route found for "GET /css/main.css" (uncaught exception)
My .htaccess in public_html is:
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# DEV ENVIRONMENT #
RewriteRule ^$ Symfony/web/app_dev.php [QSA]
RewriteRule ^(.*)$ Symfony/web/app_dev.php/$1 [QSA,L]
# PROD ENVIRONMENT #
#RewriteRule ^$ Symfony/web/app.php [QSA]
#RewriteRule ^(.*)$ Symfony/web/app.php/$1 [QSA,L]
Any suggestions how to make things right?
Interesting problem. After digging around the code I found following solution.
Create a class named PathPackage.php in src/Vendor/YourBundle/Templating/Asset folder with following code.
<?php
namespace Vendor\YourBundle\Templating\Asset;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Templating\Asset\PathPackage as BasePathPackage;
class PathPackage extends BasePathPackage
{
/**
* Constructor.
*
* #param Request $request The current request
* #param string $version The version
* #param string $format The version format
*/
public function __construct(Request $request, $version = null, $format = null)
{
parent::__construct("/Symfony", $version, $format);
}
}
Then in your app/config/config.yml add the following parameter.
parameters:
// ...
templating.asset.path_package.class: Vendor\YourBundle\Templating\Asset\PathPackage
Now it will append /Symfony to the asset url parameter.
To summarize asset twig function calls getUrl method to determine the url. Which is extended by this class. Object of the class is passed as argument during templating.helper.assets service creation. Luckily PathPackage class is configurable. So solution was possible :).
Do php app/console assets:install ./web locally, and upload the content of web folder your remote shared hosting.

Resources