Redirecionamento HTTPS com falha para alguns URLs, mas não para outros

1

O redirecionamento de HTTP para HTTPS acontece corretamente quando o URL é um dos seguintes:

  • http://example.com > > https://example.com [OK]
  • http://www.example.com > > https://example.com [OK]
  • http://www.example.com/login > > https://example.com/login [OK]

No entanto, o redirecionamento para HTTPS falha quando o URL é assim:

  • http://example.com/login > > erro (veja screenshot)

Porfavor,informesobrecomoresolver.

Códigoeconfiguraçãoabaixo.Obrigadoantecipadamente...

Outrosdetalhes:

  • Ubuntu16.04
  • Apache2.4
  • omod_rewriteestáativado
  • Laravel5.3
  • cachedonavegadorlimpo

arquivo.htaccess

<IfModulemod_rewrite.c><IfModulemod_negotiation.c>Options-MultiViews</IfModule>RewriteEngineOn#AllowBloginSub-DirectoryRewriteCond$1!^(blog)#Redirecttonon-WWWRewriteCond%{HTTP_HOST}^www.example.com$RewriteRule^(.*)https://example.com/$1[QSA,L,R=301]#RedirectTrailingSlashesIfNotAFolder...RewriteCond%{REQUEST_FILENAME}!-dRewriteRule^(.*)/$/$1[L,R=301]#HandleFrontController...RewriteCond%{REQUEST_FILENAME}!-dRewriteCond%{REQUEST_FILENAME}!-fRewriteRule^index.php[L]#HandleAuthorizationHeaderRewriteCond%{HTTP:Authorization}.RewriteRule.*-[E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]</IfModule>

ConfiguraçãodoHostVirtual

(example.com.conf)

<VirtualHost*:80>ServerNameexample.comServerAliasexample.comServerAdminsupport@example.comDocumentRoot/var/www/example.com_dev/public<Directory"/var/www/example.com_dev/public">
                DirectoryIndex index.php
                AllowOverride All
                Order allow,deny
                Allow from all
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<VirtualHost *:80>
        ServerName example.com
        ServerAlias www.example.com
        ServerAdmin [email protected]
        DocumentRoot /var/www/example.com_dev/public
        <Directory "/var/www/example.com_dev/public">
                DirectoryIndex index.php
                AllowOverride All
                Order allow,deny
                Allow from all
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Configuração do Host Virtual

(exemplo-ssl.com.conf)

<IfModule mod_ssl.c>
    <VirtualHost _default_:443>
    ServerAdmin [email protected]
        ServerName example.com
        ServerAlias example.com
        DocumentRoot /var/www/example.com_dev/public
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        SSLEngine on
        SSLCertificateFile /etc/apache2/ssl/example_com.crt
        SSLCertificateKeyFile /etc/apache2/ssl/example_com.key
        SSLCertificateChainFile /etc/apache2/ssl/example_com.ca-bundle
        <FilesMatch "\.(cgi|shtml|phtml|php)$">
            SSLOptions +StdEnvVars
        </FilesMatch>
        <Directory /usr/lib/cgi-bin>
            SSLOptions +StdEnvVars
        </Directory>
        <Directory "/var/www/example.com_dev/public">
            DirectoryIndex index.php
            AllowOverride All
            Order allow,deny
            Allow from all
        </Directory>
        BrowserMatch "MSIE [2-6]" \
            nokeepalive ssl-unclean-shutdown \
            downgrade-1.0 force-response-1.0
        BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
    </VirtualHost>
</IfModule>

<IfModule mod_ssl.c>
    <VirtualHost _default_:443>
    ServerAdmin [email protected]
        ServerName example.com
        ServerAlias www.example.com
        DocumentRoot /var/www/example.com_dev/public
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        SSLEngine on
        SSLCertificateFile /etc/apache2/ssl/example_com.crt
        SSLCertificateKeyFile /etc/apache2/ssl/example_com.key
        SSLCertificateChainFile /etc/apache2/ssl/example_com.ca-bundle
        <FilesMatch "\.(cgi|shtml|phtml|php)$">
            SSLOptions +StdEnvVars
        </FilesMatch>
        <Directory /usr/lib/cgi-bin>
            SSLOptions +StdEnvVars
        </Directory>
        <Directory "/var/www/example.com_dev/public">
            DirectoryIndex index.php
            AllowOverride All
            Order allow,deny
            Allow from all
        </Directory>
        BrowserMatch "MSIE [2-6]" \
            nokeepalive ssl-unclean-shutdown \
            downgrade-1.0 force-response-1.0
        BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
    </VirtualHost>
</IfModule>

// Redirecionamento no nível do aplicativo

(app / Http / middleware / HttpsProtocol.php - Laravel 5.3)

<?php

namespace App\Http\Middleware;

use Closure;

class HttpsProtocol
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(!$request->secure()){
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request);
    }
}

Kernel HTTP no nível do aplicativo

(app / Http / Kernel.php - Laravel 5.3)

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\HttpsProtocol::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
}
    
por eric 03.04.2017 / 20:09

2 respostas

2

Resolvido. O problema foi que o host 000-default.conf virtual ainda estava ativo (ativado) e interceptando as solicitações como http://example.com/* . Uma vez que foi desativado usando:

a2dissite 000-default.conf 

tudo começou a funcionar como esperado.

    
por 04.04.2017 / 18:57
0
  • http://example.com >> https://example.com [OK]
  • http://example.com/login >> error (see screenshot)

De seu dump de código, não consigo ver onde essas situações são tratadas (embora você diga que o primeiro funciona OK)?

Desde que você parece estar fazendo o redirecionamento www em .htaccess :

#Redirect to non-WWW
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteRule ^(.*) https://example.com/$1  [QSA,L,R=301]

Você pode tentar alterar isso para:

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com
RewriteRule (.*) https://example.com/$1  [R=301,L]

Isso incorpora a verificação de HTTP. Portanto, se HTTP ou www , redirecione para HTTPS sem www .

Você precisará limpar todos os caches antes do teste, pois 301s incorretos terão sido armazenados em cache pelo navegador.

Você parece ter duplicado ambos os hosts virtuais para as portas 80 e 443? Isso pode estar contribuindo para o seu problema. Você só precisa de um VirtualHost para a porta 80 e um para a porta 443:

ServerName example.com
ServerAlias example.com

Deve ser:

ServerName example.com
ServerAlias www.example.com

Como você tem para o duplicado . (Em seguida, exclua a duplicata.)

    
por 03.04.2017 / 21:08