2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Laravel】HerokuでHTTPSを強制しつつベーシック認証をかける

Last updated at Posted at 2020-03-11

環境

  • Laravel Framework 6.14.0

結論

アプリケーションに.htaccessファイル.htpasswdファイルを含めてgit pushします。
.htaccessファイルについては既に存在しているため、HTTPSリダイレクトの設定ベーシック認証の設定を追記します。
.htpasswdのパスですが、Herokuではアプリケーションディレクトリが/appとなるため、アプリケーション直下にファイルを作った場合、/app/.htpasswdで参照できます。

/public/.htaccess
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # !!! 追記 BEGIN !!!

    # HTTPアクセスのみをHTTPSにリダイレクトする
    # 「RewriteCond %{HTTPS} off」だとリダイレクトループが発生するので注意
    # 301リダイレクトで旧URLが持っているGoogleからの評価を引き継ぐ
    RewriteCond %{HTTP:X-Forwarded-Proto} ^http$
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    # HTTPSアクセスの場合のみベーシック認証を行う 
    <If "%{HTTP:X-Forwarded-Proto} == 'https'">
        AuthUserFile /app/.htpasswd
        AuthType Basic
        AuthName "Restricted Access"
        Require valid-user
    </If>

    # !!! 追記 END !!!

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>
/.htpasswd
# test:test
test:NcOjoYwcay98.

ルートディレクトリの根拠


$ heroku run bash
~ $ pwd
/app
~ $ ls
Procfile   artisan	  composer.lock  package.json  resources   storage  webpack.mix.js
README.md  bootstrap	  config	 phpunit.xml   routes	   tests
app	   composer.json  database	 public        server.php  vendor

関連記事

【Laravel】Herokuでベーシック認証をかける
https://qiita.com/hiro-chika/items/1bdb5ef0c9fb990f4de4

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?