LoginSignup
0
0

More than 1 year has passed since last update.

Herokuでリダイレクトする方法(Python3・Flask)

Posted at

TL;DR

  • Herokuでは.htaccessによるリダイレクトが動作しなかった。
  • flask.redirectを使ってゴリ押しする。

.htaccessについて(不可)

[Heroku]herokuでhttpでのアクセスをhttpsへリダイレクトさせる設定など、複数のサイトを参考に以下のように作成・アップロードした。

.htaccess
# リダイレクトを設定する宣言
RewriteEngine on
# X-Forwarded-Protoが設定されているときに作動
RewriteCond %{HTTP:X-Forwarded-Proto} ^http$
# HOST,URIを指定して転送
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

httpでアクセスしたが、転送されなかった。
原因については不明だが、Pythonを使っているなどの環境が悪い気がする。

flask.redirectについて(可)

PythonのFlaskでhttpからhttpsにリダイレクトするを参考に、以下のように作成した。

from flask import Flask, redirect

app = Flask(__name__) # おまじない

# デコレーターを設定
@app.before_request
def before_request():
    # httpでアクセスしているとき・開発環境のとき以外で作動
    if not request.is_secure and app.env != 'development':
        # URLの"http"を"https"に置き換え
        url = request.url.replace('http://', 'https://', 1)
        # レスポンスステータスコードを"301"に設定
        code = 301
        # 転送
        return redirect(url, code=code)

# (略)

httpでアクセスすると、301リダイレクトされる。

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