8-3. Webアプリケーションのサーバー公開(CGI運用)

.htaccess によるリダイレクトとCGI実行設定

ブラウザからのすべてのアクセスを Python のエントリーポイント(index.cgi)へ集約します。

Apache

# ~/public_html/python-lab.net/.htaccess

Options +ExecCGI
AddHandler cgi-script .cgi

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.cgi/$1 [QSA,L]

エントリーポイント(index.cgi)の作成

Flask アプリケーションを CGI 経由で動作させるスクリプトを作成します。

Python

#!/home/c1234567/public_html/python-lab.net/venv/bin/python3
# -*- coding: utf-8 -*-

import sys
import os
from wsgiref.handlers import CGIHandler

# 仮想環境のパスとアプリのパスを追加
sys.path.insert(0, os.path.dirname(__file__))

# Flask アプリのインポート (例: app.py の app オブジェクト)
from app import app

if __name__ == "__main__":
    CGIHandler().run(app)

パーミッション設定と500エラーの対処

CGIスクリプトを動作させるには、適切なファイルパーミッションの設定が必須です。

Bash

# index.cgi に実行権限を付与
chmod 755 index.cgi

# .htaccess のパーミッション確認
chmod 644 .htaccess

⚠️ 500 Internal Server Error が発生した場合のチェックリスト

  1. index.cgi の1行目(シバング: #!/...)のPythonパスが正しいか
  2. index.cgi の改行コードが LF になっているか(CRLF だとエラーになります)
  3. コントロールパネルの「エラーログ(error_log)」でスタックトレースを確認する

コメント

タイトルとURLをコピーしました