Make Laravel use HTTPs by default - laravel

I deployed my website, and used this code to enforce that the protocol used is HTTPs
\Illuminate\Support\Facades\URL::forceScheme('https');
in the AppServiceProvider.
When I visit my website, it uses HTTP by default and I have to manually change 'http' to 'https' in the address bar and then the SSL certificate works fine and I can fill all forms securely.
How can I enforce that when the user visits the website, HTTPs runs not HTTP

Pls try this,
Create file HttpsProtocol.php locate in app/Http/Middleware, add below code:
<?php
namespace App\Http\Middleware;
use Closure;
class HttpsProtocol {
public function handle($request, Closure $next)
{
if (!$request->secure()) {
return redirect()->secure('/');
}
return $next($request);
}
}
?>
add this line to $middlewareGroups section in app/Http/Kernel.php
\App\Http\Middleware\HttpsProtocol::class,
Enjoy!

Add this tag to your root page head section.(home.blade.php,welcome.blade.php ...)
<head>
... other tags
#if(env('APP_ENV') === 'production')
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
#endif
</head>
And inside boot function app/Providers/AppServiceProvider.php Add :
public function boot()
{
if (env('APP_ENV') === 'production') {
$this->app['request']->server->set('HTTPS', true);
}
}
}

I used \Illuminate\Support\Facades\URL::forceScheme('https');
however, my first page was still loaded in HTTP and other subsequent requests were in HTTPs.
To fix this, I redirected the route at "/" to a clone route "/welcome" which returns the view which "/" was supposed to return.
From that point onwards HTTPs is used.
I could not redirect HTTP to HTTPs in the server because I use Elastic beanstalk and the proposed commands in the /.ebextensions config file didnt work, so my solution is as close to fixing the problem as I could get

Related

Web landing page is not connected to HTTPS

I have a problem, my website is running on Laravel 5, I have set up SSL cert and configured it using Load Balancer in AWS. Set up listeners for HTTP(80) and HTTPS(443). SSL checker seems fine. I can access https://www.mydomainname.com and it directs to a secure page.
However everytime I enter www.mydomainname.com on any browser it leads to a not secure page, when I navigate to another page like mydomainname.com/business its secured.
My AppServiceProvider conf:
public function boot()
{
if($this->app->environment('production')) {
\URL::forceScheme('https');
}
}
\URL::forceScheme('https'); will not redirect to https, it is used to build links with https inside app.
If you want redirect in Laravel you can use middleware:
public function handle($request, Closure $next) {
if (!$request->secure()) {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
Of course, the best way is to use redirect with apache/nginx.

Laravel maintenance mode on specific subdomain

I know that you can except some URIs of your main app like if you want to except example.com/page, you can just simply add it to the CheckForMaintenanceMode.php, like this:
In app/Http/Middleware/CheckForMaintenanceMode.php
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware;
class CheckForMaintenanceMode extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* #var array
*/
protected $except = [
'/page'
];
}
Now, my app has a couple subdomains using one app; I have a subdomain for my main app: app.example.com, a subdomain for my API endpoints: api.example.com and the main website: www.example.com
How can I possibly except the specific subdomain instead of URI for maintenance mode? Like having api.example.com and app.example.com in maintenance mode but not the main website www.example.com?
I'm trying to figure out it on my own and even make my own middleware just to do this, but is it possible to do this using the built-in maintenance mode of laravel with php artisan:down?
Something like:
// app.example.com and api.example.com is in maintenance mode except:
protected $except = [
'example.com'
'www.example.com'
];
See the Illuminate\Foundation\Http\Middleware\CheckMaintenanceMode middleware class:
It checks the elements of the $except property using the function fullUrlIs() from the Illuminate\Http\Request class, which itself calls the Str::is() helper (also known as the str_is() function if you're using Laravel helper function globals):
protected function inExceptArray($request)
{
foreach ($this->except as $except) {
if ($except !== '/') {
$except = trim($except, '/');
}
if ($request->fullUrlIs($except) || $request->is($except)) {
return true;
}
}
return false;
}
See https://laravel.com/docs/7.x/helpers#method-str-is
You should then be able to check for an url like this, to exclude this domain from the maintenance mode (i.e. it will always be up):
protected $except = [
'https://www.example.com/*'
];
Suppose you have two domains. One is the main domain
and another one is a subdomain.
mydomain.com
admin.mydomain.com
You have a page name maintenance. The maintenance page is under the main domain. The URL of the maintenance page is mydomain.com/maintenance.
In the maintenance mode, you will have the route permission of mydomain.com/maintenance and admin.mydomain.com
Now work process.
Goto App\Http\Middleware the open the PreventRequestsDuringMaintenance middleware then add this code
protected $except = [
'maintenance*',
'http://admin.*',
'https://admin.*'
];
Then go to App\Exceptions open Handler file, inside render function add
if (App::isDownForMaintenance()) {
return redirect('/maintenance');
}
Now run php artisan down

Laravel 5 - redirect

I'am studying laravel 5 and I have an error with a route redirect.
I have a controller with two functions:
class MainController extends Controller
{
public function index() {
//Some code
return view('index.main',compact('someDatas');
}
public function update(Request $request) {
//Some code here
return redirect(route('main'));
}
}
Here is my route.php
Route::get('/', "main\MainController#index") -> name('main');
Route::get('/update', "main\MainController#update") -> name('update');
In my main.blade.php view, I have a link with a redirect to an update update route:
{{$source -> nom}}
When I click on the link, I get an error:
The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.
The URL is https://127.0.0.1:8000/update, but when i remove the 's' of HTTPS I'm redirected to the main menu.
I don't understand why this error happens, I have other applications with similar code that work fine.
Thanks for your time and your responses!
This has probably nothing to do with Laravel. When you use HTTPS is tries to use a secure connection. But, you probably do not have a valid certificate for your "localhost" domain. So, you will usually get warnings. I googled your error and found the following: https://support.mozilla.org/nl/questions/1117296 It probably has something to do with your Anti Virus software.
When you use HTTP it will not try to use a secure connection and not verify de site you are connecting to. Which is the reason it works. You should use HTTP for localhost and HTTPS for production.
So again, this has nothing to do with Laravel or your code. It is something to do with HTTPS SSL and certificates. So try using HTTP instead for local development.
Try this way it's working for me.
web.php
Route::match(['get','post'],'/admin/edit_users/{id}','UsersController#EditUser');
user.blade.php
<td><a href="{{ url('/admin/edit_users',$user->id)}}">
<i class="icon icon-edit " style="font-size: 20px;color:green;"></i></a></td>
UsersController.php
public function EditUser(Request $request,$id){
$user=User::where(['id'=>$id])->first();
if($request->isMethod('post')){
$data= array('fname' =>$request->input('fname'),
'lname' =>$request->input('lname'),
'contact' =>$request->input('contact'),
);
$upatedata= DB::table('users')->where('id', $id)->update($data);
if($upatedata){
return redirect('admin/users')->with('flash_message_success','User has been update Successfully');
}else{
return redirect('admin/users')->with('flash_message_error','Incorrect User Data');
}
}
return view('admin.users.edit_user',compact('user'));
}

Laravel custom redirect if user is not logged in?

I have on my project route groups for 4 subdomains, on one subdomain I set 'middleware' => 'auth', it works, but if guest try to access this protected subdomain he is redirected to sub.project.com/login and not to project.com/login, where can I set it correctly?
You can try to handle the redirect within the middleware
public function handle($request, Closure $next, $guard = null)
{
if ($request->getPort() != 80 || Auth::guard($guard)->guest()) {
//to account for json or ajax requests
if ($request->ajax() || $request->wantsJson())
{
return response('Unauthorized.', 401);
}
return redirect('auth/login')->withErrors(['must login']);
}
return $next($request);
}
By default it shouldn't be a problem. On by default I mean, you had to explicitly tell Laravel where to redirect, if you didn't do so (didn't alter middleware logic in any way), there are 3 things that come in play:
Your .htaccess (or httpd.conf) is messed up.
Certificate issues. Do you have SSL enabled on the login page? If the website config file points to a cert issued for not the same domain, it causes such problems.
config/app.php includes the wrong domain
(It's a stupid question on my part, but could you please confirm that it redirects to and not renders the content available on that subdomain? To exclude some possibilities.)

Why codeIgniter duplicating and appending URL?

When I moved my working CI webapp from my localhost to a webhosting, I encounter a "duplicating and appending URL" problem.
In my localhost, this works (shows the login page): http://mylocal/someapp/ --> which will redirect to http://mylocal/someapp/index.php/login
However, after migrating to webhosting, trying to access it like this: http://webhosting.com/someapp/, somehow it automatically appends to be
http://webhosting.com/someapp/%20//webhosting.com/someapp/index.php/login
My .htaccess contains nothing (works on localhost)
In config.php,
$config['base_url']= '';
The home controller which will redirect to the login controller (then the login view) looks like this:
class Home extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$this->load->view('home_view', $data);
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
function logout()
{
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('home', 'refresh');
}
}
Or maybe some settings in the webhosting that I need to configure?
Use http:// prefix before base url in $config['base_url'];
e.g.
$config['base_url']=http://localhost/islam;
$config['base_url']= '';
should contain the base url of your website. i think that's the problem.
should be:
$config['base_url']= 'http://yoursite.com/';
Found the answer my self. Turns out that some webhostings are not treating CI refresh properly.
header("Refresh:0;url=...");
instead, it only wants this:
header("Location: ...");
So, I changed url_helper.php (system/helpers/url_helper.php line:543), from
case 'refresh'
to
case 'xxxrefresh'
so that it always skips the header refresh and only use header location.
I don't know if this the proper solution, but it works on my website.
Test your webhosting characteristics before you migrate your CodeIgniter codes from your local machine.
Hope this helps somebody in the future.
I had the same "duplication problem" with a local insallation. Here is my solution: set your base URL in application/config/config.php, for example:
$config['base_url'] = 'http://localhost/ci/';
It is important to add the http:// or https:// prefix to fix the "duplication problem". Of course, the trailing slash is also necessary.

Resources