programing

Laravel Project가 모든 루트에 HTTPS를 사용하도록 강제하려면 어떻게 해야 합니까?

randomtip 2022. 10. 22. 09:44
반응형

Laravel Project가 모든 루트에 HTTPS를 사용하도록 강제하려면 어떻게 해야 합니까?

저는 안전한 연결이 필요한 프로젝트를 진행하고 있습니다.

다음을 통해 'https'를 사용하도록 루트, uri, 자산을 설정할 수 있습니다.

Route::get('order/details/{id}', ['uses' => 'OrderController@details', 'as' => 'order.details', 'https']);

url($language.'/index', [], true)

asset('css/bootstrap.min.css', true)

하지만 항상 파라미터를 설정하는 것은 피곤한 것 같습니다.

모든 루트에 HTTPS 링크를 강제로 생성하는 방법이 있습니까?

이를 boot() 메서드의 AppServiceProvider에 배치합니다.

if($this->app->environment('production')) {
    \URL::forceScheme('https');
}

여기 몇 가지 방법이 있습니다.가장 편리한 것을 선택하세요.

  1. 모든 비보안 요청을 https로 리디렉션하도록 웹 서버를 구성합니다.nginx 설정의 예:

    server {
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name example.com www.example.com;
        return 301 https://example.com$request_uri;
    }
    
  2. 합니다.APP_URL https: 명령어:

    APP_URL=https://example.com
    
  3. 도우미 secure_url() 사용(Laravel5.6)

  4. AppServiceProvider::boot() 메서드에 다음 문자열을 추가합니다(버전 5.4 이상의 경우).

    \Illuminate\Support\Facades\URL::forceScheme('https');
    

업데이트:

  1. 루트 그룹의 암묵적인 설정 방식(Laravel 5.6):

    Route::group(['scheme' => 'https'], function () {
        // Route::get(...)->name(...);
    });
    

설정할 수 .'url' => 'https://youDomain.com'config/app.php또는 미들웨어 클래스 Larabel 5 - HTTPS로 리디렉션할 수 있습니다.

은 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★web.php ★★★★★★★★★★★★★★★★★」api.php완벽하게 작동했습니다.

URL::forceScheme('https');

.htaccess 파일에서 다음 코드를 사용하면 방문자가 사이트의 HTTPS 버전으로 자동으로 리디렉션됩니다.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Larabel 7.x (2020)에서의 강제 Https


"2020 업데이트? Url::force Scheme은 나를 위해 펑키한 행동을 했지만, 이것은 매우 효과적이었습니다."


  1. https 코드 스니펫

    해결(\Iluminate\)라우팅\UrlGenerator:: class)-> forceScheme('https');


  1. 임의의 서비스 프로바이더의 부트 방식 내에 그 스니펫을 추가한다.

  • : : 픈픈 app/providers/RouteServiceProvider.php
  • 2: 다음으로 부트 방식에 https 코드 스니펫을 추가합니다.
    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        resolve(\Illuminate\Routing\UrlGenerator::class)->forceScheme('https');

        parent::boot();
    }
  • 3: 마지막 실행php artisan route:clear && composer dumpautoloadLaravel의 캐시된 경로와 캐시된 서비스 공급자를 클리어합니다.

이것을 .htaccess 코드에 추가합니다.

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]

www.yourdomain.com 를 도메인명으로 바꿉니다.그러면 도메인의 모든 URL이 https를 사용하도록 강제됩니다.도메인에 https 인증서가 설치 및 구성되어 있는지 확인합니다.녹색으로 표시된 https가 안전한 것으로 표시되지 않으면 chrome에서 f12 키를 누르고 콘솔 탭의 혼합 오류를 모두 수정합니다.

이게 도움이 됐으면 좋겠네요!

나는 더 좋다forceScheme.그래서 라라벨 앱이 책임져야 합니다.

때문에 방법은 이 안에 있는 if 문장이 if 문장이 만약 if 문장이 만약 If 문장으로 입니다.bootapp/Providers/AppServiceProvider.php

    if (env('APP_ENV') === 'production') {
        \Illuminate\Support\Facades\URL::forceScheme('https');
    }

APP_ENV: APP_ENV입니다.서버로 를 입력합니다.env

이것은 Larabel 5에서 테스트되었습니다.구체적으로는 5.6입니다.

public function boot()
{
  if(config('app.debug')!=true) {
    \URL::forceScheme('https');
  }
}

앱/프로바이더/앱 서비스 프로바이더로 이동합니다.php

larabel 8의 경우 위의 모든 방법을 시도했지만 브라우저에 오류가 너무 많이 리다이렉트된 경우 에서 프록시를 설정하십시오.TrustProxies다음과 같은 미들웨어:

앱\Http\미들웨어\Trust Proxies.php

/**
  * The trusted proxies for this application.
  *
  * @var array|string|null
*/
protected $proxies = '*';

.env 파일에서는

FORCE_HTTPS=true

이것은 나에게 효과가 있었습니다.또한 추가 절차로 APP URL을 https://your-site.com로 설정할 수도 있습니다.

부하가 분산된 인프라에서 이 작업을 수행하는 방법을 알아냈습니다.

Nginx 설정을 추가해야 합니다.

location ~ \.php$ {
            include snippets/fastcgi-php.conf;
    #       # With php-fpm (or other unix sockets):
            fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;

            add_header X-Forwarded-Proto https;
            add_header X-Forwarded-Port 443;
            add_header Ssl-Offloaded "1";
            add_header Access-Control-Allow-Origin "*";
            fastcgi_param  HTTPS "on";
            fastcgi_param  HTTP_X_FORWARDED_PROTO "https";
    }

임포터 피스는 add_headers와 pastcgi_params로 AWS 로드밸런서를 통해 매력적으로 동작합니다.

여기 또 다른 옵션이 있습니다.larabel 8.*에서 동작합니다.단, 낮은 버전은 잘 모르겠습니다.

를 추가합니다.ASSET_URL변하기 쉬운.env파일.

예를 들어 다음과 같습니다.

ASSET_URL=https://secure-domain.com

자세한 내용은 Laravel Helpers를 참조하십시오.

힌트: 위 링크의 코멘트에 주의해 주세요.

Route Service Provider 파일에서 동작합니다.

    $url = \Request::url();
    $check = strstr($url,"http://");
    if($check)
    {
       $newUrl = str_replace("http","https",$url);
       header("Location:".$newUrl);

    }

이 문제를 해결하는 더 좋은 방법은 다음과 같습니다. -> 퍼블릭폴더로 이동하여 -> 편집.htaccess는 아래에 이 코드를 추가합니다.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

-> 및 저장 -> 브라우저를 닫았다가 다시 엽니다.

파일 app\Providers\AppServiceProvider의 클래스 이름 앞에 추가합니다.php

use Illuminate\Support\Facades\URL;

그런 다음 이 코드를 app\Providers\AppServiceProvider.php 파일의 부트 함수 안에 붙여넣습니다.

if (config('app.env') === 'production') {
    URL::forceScheme('https');
}

.htaccess 파일을 사용하여https 리다이렉트를 실행하는 것은 어떨까요?이것은 (not in public folder)에 배치해야 합니다.프로젝트 루트 디렉토리를 가리키도록 서버를 구성해야 합니다.

<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>

Apache 서버를 사용하고 있는데 가상 호스트 구성을 변경하는 것이 가장 효율적이라고 생각합니다.이렇게 바꿔주세요.

<VirtualHost *:80>
   ServerName www.yourdomain.com
   Redirect / https://www.yourdomain.com
</VirtualHost>

<VirtualHost _default_:443>
   ServerName www.yourdomain.com
   DocumentRoot /usr/local/apache2/htdocs
   SSLEngine On
# etc...
</VirtualHost>

larabel 5.2의 secure_url() 함수를 사용합니다.

$url = secure_url('user/profile');

{{ secure_url('your-link') }} //instead url()

참조 larabel secure_url() 함수

언급URL : https://stackoverflow.com/questions/35827062/how-to-force-laravel-project-to-use-https-for-all-routes

반응형