define('ROUTE_BASE', 'lumen/public');
$app->get(ROUTE_BASE . '/', function () use ($app) {
return $app->welcome();
});
$app->get(ROUTE_BASE . '/test', function () use ($app) {
return 'test data : 123 abc !';
});
When I access 'localhost/lumen/public/' I can see the 'lumen welcome page'.
But if I try to access 'localhost/lumen/public/test', I receive the following error.
Error: its not found(404).
Laravel expects the public directory to be the webroot of your domain. As this is not true in your case, you will need to make some alterations to your .htaccess.
Options +FollowSymLinks
RewriteEngine On
RewriteBase /lumen/public
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
Also worth noting that instead of using a constant, you can use route groups to achieve the same functionality in your routes.php.
$app->group(['prefix' => 'lumen/public'], function ($app) {
$app->get('/', function () {
//welcome
});
$app->get('test', function () {
return 'test data : 123 abc !';
});
});
your lumen project must be put in webroot of your localhost,domain or virtual host not in subfolder of your webroot without edit your .htaccess.
for access your project in browser : http://lumen.laravel.dev not http://lumen.laravel.dev/public/
I hope this help. sorry for my English :)
I have a form using model-binding to enter data into a database. I'm trying to serve it over https but can't figure it out.
Here's the view:
{!! Form::model(new App\MissingHours, ['route' => ['missinghours.store'], 'class' => 'form-horizontal']) !!}
#include('missinghours/_form', ['submit_text' => 'Submit Hours'])
{!! Form::close() !!}
I've tried setting the url to https://appurl/missinghours/store but that clearly didn't work. I also tried model_secure taking after Form::open_secure, and that didn't work. When I serve the page over https and try to submit the form, I get a warning about it being un-secure and the data is not submitted.
Controller:
$input = Input::all();
$save = MissingHours::create( $input );
If you need your whole site to be https - including forms, you can Insert the following codes below RewriteEngine On on your public/.htaccess file:
RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
EDIT:
You can create a before middleware like so:
<?php
namespace App\Http\Middleware;
use Closure;
class BeforeMiddleware
{
public function handle($request, Closure $next)
{
if (! $request->secure()) return redirect()->secure($request->getRequestUri());
return $next($request);
}
}
And then use that middleware in your form.
More on Laravel Middlewares here.
Working on my first Laravel 5 project and not sure where or how to place logic to force HTTPS on my app. The clincher here is that there are many domains pointing to the app and only two out of three use SSL (the third is a fallback domain, long story). So I'd like to handle this in my app's logic rather than .htaccess.
In Laravel 4.2 I accomplished the redirect with this code, located in filters.php:
App::before(function($request)
{
if( ! Request::secure())
{
return Redirect::secure(Request::path());
}
});
I'm thinking Middleware is where something like this should be implemented but I cannot quite figure this out using it.
Thanks!
UPDATE
If you are using Cloudflare like I am, this is accomplished by adding a new Page Rule in your control panel.
You can make it works with a Middleware class. Let me give you an idea.
namespace MyApp\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\App;
class HttpsProtocol {
public function handle($request, Closure $next)
{
if (!$request->secure() && App::environment() === 'production') {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
Then, apply this middleware to every request adding setting the rule at Kernel.php file, like so:
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
// appending custom middleware
'MyApp\Http\Middleware\HttpsProtocol'
];
At sample above, the middleware will redirect every request to https if:
The current request comes with no secure protocol (http)
If your environment is equals to production. So, just adjust the settings according to your preferences.
Cloudflare
I am using this code in production environment with a WildCard SSL and the code works correctly. If I remove && App::environment() === 'production' and test it in localhost, the redirection also works. So, having or not a installed SSL is not the problem. Looks like you need to keep a very hard attention to your Cloudflare layer in order to get redirected to Https protocol.
Edit 23/03/2015
Thanks to #Adam Link's suggestion: it is likely caused by the headers that Cloudflare is passing. CloudFlare likely hits your server via HTTP and passes a X-Forwarded-Proto header that declares it is forwarding a HTTPS request. You need add another line in your Middleware that say...
$request->setTrustedProxies( [ $request->getClientIp() ] );
...to trust the headers CloudFlare is sending. This will stop the redirect loop
Edit 27/09/2016 - Laravel v5.3
Just need to add the middleware class into web group in kernel.php file:
protected $middlewareGroups = [
'web' => [
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
// here
\MyApp\Http\Middleware\HttpsProtocol::class
],
];
Remember that web group is applied to every route by default, so you do not need to set web explicitly in routes nor controllers.
Edit 23/08/2018 - Laravel v5.7
To redirect a request depending the environment you can use App::environment() === 'production'. For previous version was
env('APP_ENV') === 'production'.
Using \URL::forceScheme('https'); actually does not redirect. It just builds links with https:// once the website is rendered.
An other option that worked for me, in AppServiceProvider place this code in the boot method:
\URL::forceScheme('https');
The function written before forceSchema('https') was wrong, its forceScheme
Alternatively, If you are using Apache then you can use .htaccess file to enforce your URLs to use https prefix. On Laravel 5.4, I added the following lines to my .htaccess file and it worked for me.
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
for laravel 5.4 use this format to get https redirect instead of .htaccess
namespace App\Providers;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
URL::forceScheme('https');
}
}
What about just using .htaccess file to achieve https redirect? This should be placed in project root (not in public folder). Your server needs to be configured to point at project root directory.
<IfModule mod_rewrite.c>
RewriteEngine On
# Force SSL
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Remove public folder form URL
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
I use this for laravel 5.4 (latest version as of writing this answer) but it should continue to work for feature versions even if laravel change or removes some functionality.
Similar to manix's answer but in one place. Middleware to force HTTPS
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class ForceHttps
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!app()->environment('local')) {
// for Proxies
Request::setTrustedProxies([$request->getClientIp()],
Request::HEADER_X_FORWARDED_ALL);
if (!$request->isSecure()) {
return redirect()->secure($request->getRequestUri());
}
}
return $next($request);
}
}
This is for Larave 5.2.x and greater. If you want to have an option to serve some content over HTTPS and others over HTTP here is a solution that worked for me. You may wonder, why would someone want to serve only some content over HTTPS? Why not serve everything over HTTPS?
Although, it's totally fine to serve the whole site over HTTPS, severing everything over HTTPS has an additional overhead on your server. Remember encryption doesn't come cheap. The slight overhead also has an impact on your app response time. You could argue that commodity hardware is cheap and the impact is negligible but I digress :) I don't like the idea of serving marketing content big pages with images etc over https. So here it goes. It's similar to what others have suggest above using middleware but it's a full solution that allows you to toggle back and forth between HTTP/HTTPS.
First create a middleware.
php artisan make:middleware ForceSSL
This is what your middleware should look like.
<?php
namespace App\Http\Middleware;
use Closure;
class ForceSSL
{
public function handle($request, Closure $next)
{
if (!$request->secure()) {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
Note that I'm not filtering based on environment because I have HTTPS setup for both local dev and production so there is not need to.
Add the following to your routeMiddleware \App\Http\Kernel.php so that you can pick and choose which route group should force SSL.
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'forceSSL' => \App\Http\Middleware\ForceSSL::class,
];
Next, I'd like to secure two basic groups login/signup etc and everything else behind Auth middleware.
Route::group(array('middleware' => 'forceSSL'), function() {
/*user auth*/
Route::get('login', 'AuthController#showLogin');
Route::post('login', 'AuthController#doLogin');
// Password reset routes...
Route::get('password/reset/{token}', 'Auth\PasswordController#getReset');
Route::post('password/reset', 'Auth\PasswordController#postReset');
//other routes like signup etc
});
Route::group(['middleware' => ['auth','forceSSL']], function()
{
Route::get('dashboard', function(){
return view('app.dashboard');
});
Route::get('logout', 'AuthController#doLogout');
//other routes for your application
});
Confirm that your middlewares are applied to your routes properly from console.
php artisan route:list
Now you have secured all the forms or sensitive areas of your application, the key now is to use your view template to define your secure and public (non https) links.
Based on the example above you would render your secure links as follows -
Login
SignUp
Non secure links can be rendered as
About US</li>
Get the deal now!</li>
What this does is renders a fully qualified URL such as https://yourhost/login and http://yourhost/aboutus
If you were not render fully qualified URL with http and use a relative link url('/aboutus') then https would persists after a user visits a secure site.
Hope this helps!
You can use RewriteRule to force ssl in .htaccess same folder with your index.php
Please add as picture attach, add it before all rule others
In Laravel 5.1, I used:
File: app\Providers\AppServiceProvider.php
public function boot()
{
if ($this->isSecure()) {
\URL::forceSchema('https');
}
}
public function isSecure()
{
$isSecure = false;
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
$isSecure = true;
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
$isSecure = true;
}
return $isSecure;
}
NOTE: use forceSchema, NOT forceScheme
I'm adding this alternative as I suffered a lot with this issue. I tried all different ways and nothing worked. So, I came up with a workaround for it. It might not be the best solution but it does work -
FYI, I am using Laravel 5.6
if (App::environment('production')) {
URL::forceScheme('https');
}
production <- It should be replaced with the APP_ENV value in your .env file
The easiest way would be at the application level. In the file
app/Providers/AppServiceProvider.php
add the following:
use Illuminate\Support\Facades\URL;
and in the boot() method add the following:
$this->app['request']->server->set('HTTPS', true);
URL::forceScheme('https');
This should redirect all request to https at the application level.
( Note: this has been tested with laravel 5.5 LTS )
The answers above didn't work for me, but it appears that Deniz Turan rewrote the .htaccess in a way that works with Heroku's load balancer here:
https://www.jcore.com/2017/01/29/force-https-on-heroku-using-htaccess/
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Here's how to do it on Heroku
To force SSL on your dynos but not locally, add to end of your .htaccess in public/:
# Force https on heroku...
# Important fact: X-forwarded-Proto will exist at your heroku dyno but wont locally.
# Hence we want: "if x-forwarded exists && if its not https, then rewrite it":
RewriteCond %{HTTP:X-Forwarded-Proto} .
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
You can test this out on your local machine with:
curl -H"X-Forwarded-Proto: http" http://your-local-sitename-here
That sets the header X-forwarded to the form it will take on heroku.
i.e. it simulates how a heroku dyno will see a request.
You'll get this response on your local machine:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved here.</p>
</body></html>
That is a redirect. That is what heroku is going to give back to a client if you set the .htaccess as above. But it doesn't happen on your local machine because X-forwarded won't be set (we faked it with curl above to see what was happening).
in IndexController.php put
public function getIndex(Request $request)
{
if ($request->server('HTTP_X_FORWARDED_PROTO') == 'http') {
return redirect('/');
}
return view('index');
}
in AppServiceProvider.php put
public function boot()
{
\URL::forceScheme('https');
}
In AppServiceProvider.php every redirect will be going to URL https and for HTTP request we need once redirect so in IndexController.php Just we need do once redirect.
You particularly don't need to do the work as mentioned in IndexController.php, it is an extra control on the redirection.
If you're using CloudFlare, you can just create a Page Rule to always use HTTPS:
This will redirect every http:// request to https://
In addition to that, you would also have to add something like this to your \app\Providers\AppServiceProvider.php boot() function:
if (env('APP_ENV') === 'production' || env('APP_ENV') === 'dev') {
\URL::forceScheme('https');
}
This would ensure that every link / path in your app is using https:// instead of http://.
I am using in Laravel 5.6.28 next middleware:
namespace App\Http\Middleware;
use App\Models\Unit;
use Closure;
use Illuminate\Http\Request;
class HttpsProtocol
{
public function handle($request, Closure $next)
{
$request->setTrustedProxies([$request->getClientIp()], Request::HEADER_X_FORWARDED_ALL);
if (!$request->secure() && env('APP_ENV') === 'prod') {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
A little different approach, tested in Laravel 5.7
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Str;
class ForceHttps
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ( !$request->secure() && Str::startsWith(config('app.url'), 'https://') ) {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
PS. Code updated based on #matthias-lill's comments.
You can simple go to app -> Providers -> AppServiceProvider.php
add two lines
use Illuminate\Support\Facades\URL;
URL::forceScheme('https');
as shows in the following codes:
use Illuminate\Support\Facades\URL;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
URL::forceScheme('https');
// any other codes here, does not matter.
}
For Laravel 5.6, I had to change condition a little to make it work.
from:
if (!$request->secure() && env('APP_ENV') === 'prod') {
return redirect()->secure($request->getRequestUri());
}
To:
if (empty($_SERVER['HTTPS']) && env('APP_ENV') === 'prod') {
return redirect()->secure($request->getRequestUri());
}
This worked out for me.
I made a custom php code to force redirect it to https.
Just include this code on the header.php
<?php
if (isset($_SERVER['HTTPS']) &&
($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
$protocol = 'https://';
}
else {
$protocol = 'http://';
}
$notssl = 'http://';
if($protocol==$notssl){
$url = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";?>
<script>
window.location.href ='<?php echo $url?>';
</script>
<?php } ?>
I found out that this worked for me. First copy this code in the .htaccess file.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
This work for me in Laravel 7.x in 3 simple steps using a middleware:
1) Generate the middleware with command php artisan make:middleware ForceSSL
Middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\App;
class ForceSSL
{
public function handle($request, Closure $next)
{
if (!$request->secure() && App::environment() === 'production') {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
2) Register the middleware in routeMiddleware inside Kernel file
Kernel
protected $routeMiddleware = [
//...
'ssl' => \App\Http\Middleware\ForceSSL::class,
];
3) Use it in your routes
Routes
Route::middleware('ssl')->group(function() {
// All your routes here
});
here the full documentation about middlewares
========================
.HTACCESS Method
If you prefer to use an .htaccess file, you can use the following code:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://yourdomain.com/$1 [R,L]
</IfModule>
Regards!
The easiest way to redirect to HTTPS with Laravel is by using .htaccess
so all you have to do is add the following lines to your .htaccess file and you are good to go.
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Make sure you add it before the existing(*default) code found in the .htaccess file, else HTTPS will not work.
This is because the existing(default) code already handles a redirect which redirects all traffic to the home page where the route then takes over depending on your URL
so putting the code first means that .htaccess will first redirect all traffic to https before the route takes over
I am surprised this is not working but maybe I am missing something...I am trying to access from the main page (index.php) either the login page or the signup page. I created both routes to be handled. When I click on the link, it goes to another page such as /website/login and shows not found. Here is the routes.php code:
Route::get('/', 'MainController#index');
Route::get('login', array('as' => 'login', 'uses' => 'MembersController#loadLoginView'));
Route::get('signup', array('as' => 'signup', 'uses' => 'MembersController#loadRegisterView'));
MembersController code:
<?php
class MembersController extends BaseController {
public function loadRegisterView()
{
return View::make('members.register');
}
public function loadLoginView()
{
return View::make('members.login');
}
}
and inside views I have a folder called members and inside it I got login.blade.php and register.blade.php.
Thanks for the help in advance
To remove the index.php you could use the .htaccess provided on the Laravel website:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
Be sure you're running on an Apache server with Mod_rewrite active. I'm not expert on other servers, so I can't suggest you alternative. On Laravel's website there's this snippet for Nginx:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
Have no idea on IIS server, though.
Otherwise, you'll need to keep the 'index.php' in the url, like http://www.example.com/index.php/login
I'm trying to setup a blog script on a website running on the CodeIgniter framework. I want do this without making any major code changes to my existing website's code. I figured that creating a sub domain pointing to another Controller would be the cleanest method of doing this.
The steps that I took to setup my new Blog controller involved:
Creating an A record pointing to my server's ip address.
Adding new rules to CodeIgniter's routes.php file.
Here is what I came up with:
switch ($_SERVER['HTTP_HOST']) {
case 'blog.notedu.mp':
$route['default_controller'] = "blog";
$route['latest'] = "blog/latest";
break;
default:
$route['default_controller'] = "main";
break;
}
This should point blog.notedu.mp and blog.notedu.mp/latest to my blog controller.
Now here is the problem...
Accessing blog.notedu.mp or blog.notedu.mp/index.php/blog/latest works fine, however accessing blog.notedu.mp/latest takes me to a 404 page for some reason...
My .htaccess file looks like this (the default for removing index.php from the url):
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
And my Blog controller contains the following code:
class Blog extends CI_Controller {
public function _remap($method){
echo "_remap function called.\n";
echo "The method called was: ".$method;
}
public function index()
{
$this->load->helper('url');
$this->load->helper('../../global/helpers/base');
$this->load->view('blog');
}
public function latest(){
echo "latest working";
}
}
What am I missing out on or doing wrong here? I've been searching for a solution to this problem for days :(
After 4 days of trial and error, I've finally fixed this issue!
Turns out it was a .htaccess problem and the following rules fixed it:
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
Thanks to everyone that read or answered this question.
Does blog.domain.co/blog/latest also show a 404?
maybe you could also take a look at the _remap() function for your default controller.
http://ellislab.com/codeigniter/user-guide/general/controllers.html#default
Basically, CodeIgniter uses the second segment of the URI to determine which function in the controller gets called. You to override this behavior through the use of the _remap() function.
Straight from the user guide,
If your controller contains a function named _remap(), it will always
get called regardless of what your URI contains. It overrides the
normal behavior in which the URI determines which function is called,
allowing you to define your own function routing rules.
public function _remap($method)
{
if ($method == 'some_method')
{
$this->$method();
}
else
{
$this->default_method();
}
}
Hope this helps.
have a "AllowOverride All" in the configuration file of the subdomain in apache?
without it "blog.notedu.mp/index.php/blog/latest" work perfectly, but "blog.notedu.mp/latest" no
$route['latest'] = "index";
means that the URL http://blog.example.com/latest will look for an index() method in an index controller.
You want
$route['latest'] = "blog/latest";
Codeigniter user guide has a clear explanation about routes here