Reputation: 3611
I want to redirect from http to https automatically for my Laravel app.
url is app1.domain.com
I've added the following lines to the .htaccess file in my public folder, but it doesn't seem to take effect.
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
When I type http://app1.domain.com
, the url is not redirected and stays on http
. When I click to access my app via http://app1.domain.com/auth/login
, I get a 404. If I manually add the https
to https://app1.domain.com/auth/login
, then it works, but I'd like it if could redirect to https
automatically.
.htaccess
<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]
# Added those 2 lines for ssl redirect
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
Also tried changing my laravel .env file from APP_URL=http://app1.domain.com
to APP_URL=https://app1.domain.com
, but didn't do anything.
SOLUTION
Use web server to redirect all http requests to https.
So changed my httpd.conf
file from:
<VirtualHost *:80>
ServerName www.app1.domain.com
ServerAlias app1.domain.com
ServerAdmin [email protected]
DocumentRoot /var/www/html/app1.domain.com/public
</VirtualHost>
to:
<VirtualHost *:80>
ServerName www.app1.domain.com
ServerAlias app1.domain.com
Redirect permanent / https://app1.domain.com/ <-- this line added
ServerAdmin [email protected]
DocumentRoot /var/www/html/app1.domain.com/public
</VirtualHost>
Don't forget to service httpd restart
Any ideas? Thanks
Upvotes: 1
Views: 2645
Reputation: 36
Put this in your .htaccess file
RewriteEngine On
# Redirect to https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
It worked for me.
Upvotes: 0
Reputation: 447
I use a middleware function, and just apply it to all routes. Then you can take it off if you need to for any particular url
namespace App\Http\Middleware;
use Closure;
class HttpsProtocol {
public function handle($request, Closure $next)
{
if (!$request->secure() && env('APP_ENV') === 'production') {
return redirect()->secure($request->getRequestUri(), 301);
}
return $next($request);
}
}
then add to your kernel.php file
'https' => [
'App\Http\Middleware\HttpsProtocol'
],
then just tack this on to your route like this
Route::get('/', ['middleware' => array('web','https'),'uses' => 'HomeController@index']);
or register it globally
Upvotes: 3