LoginSignup
0
0

More than 5 years have passed since last update.

slimframework3のルーティングについてハマった備忘録

Posted at

この記事について

表題の通りslimframework3をローカルの環境に導入時、ルーティングの設定にハマった際の記録。
もっと良い解決方法をご存知の方はコメント下さい。

slimframeworkのセットアップ

  1. こちらの記事を参考にslimframework3をセットアップ
  2. セットアップする際、以下にインストール。

    /ドキュメントルート/test

  3. http://localhost/test/public/ にアクセス、起動を確認

urlを短縮する

/test/.htaccess を作成。以下の記述を追加



    RewriteEngine On
    RewriteRule ^(.*)$ public/$1

/test/public/.htaccess を以下の内容に編集



  RewriteEngine On
  RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.)::\2$
  RewriteRule ^(.) - [E=BASE:%1]
  RewriteBase /test/public/
  RewriteRule ^ index.php [QSA,L]

動作を確認

動作確認のため http://localhost/test/ にアクセスするとindexページが表示される。

次にルートパラメータの動作確認で、http://localhost/test/hogehoge にアクセスすると 「Page Not Found 」と表示されてしまった

試しに、http://localhost/test/public/hogehoge にアクセスしたところ、問題なくページが表示されルートパラメータも動作を確認できた。

原因を調査

エラーページはApacheのものではなく、フレームワークのものが表示されている。

Apache側の設定でなんとかなりそうだがよくわからない為、framework側原因を調査。

こちらのページで以下の現在パス表示のコードが解決する手段になるかもみたいな記述を発見。


$route = $app->getContainer()->get('request')->getUri()->getPath();

上記コードを使用し、現在パスを表示

http://localhost/test/public/ => 結果: string(1) "/"

http://localhost/test/ => 結果: string(1) "/test/"

やはり、フレームワークのパスの解釈がそれぞれで違うのが原因でした。

対策

Apache側の設定でなんとかなりそうだがやっぱりよくわからない為、framework側でなんとかする。

ルーティングが正しく認識していないのでルーティングを変えれば良いと思われる。

ドキュメントルート/test/src/routes.php を以下の内容に修正


$app->get('/test/[{name}]', function (Request $request, Response $response, array $args) {

動作を確認!

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