LoginSignup
2
7

More than 1 year has passed since last update.

フレームワークなし、.htaccessとPHPでURLルーティングする

Last updated at Posted at 2021-06-07

フレームワークを使わずに以下のルーティングを使って自作したサイトたち

自作SNS
https://test.nieru.net/
ユーザーページサンプル
https://test.nieru.net/admin
https://test.nieru.net/nieru
(利用者募集しております。)

無料レンタル掲示板サイト
https://nieru.net/
掲示板活用サンプル
- https://nieru.net/sample
- https://nieru.net/vip
- https://nieru.net/atbs

フレームワークなし、.htaccessとPHPでURLルーティングする

フレームワーク使わないルーティングはこれでいいよねって思ったので書いてみる

フォルダ構成

ルート
┣ index.php
┣ .htaccess
┗ show
  ┗ main.html

.htaccess

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

5行目の
RewriteRule ^(.*)$ index.php/$1 [L]が重要
これを記載すればとりあえずどんなURLでも最初のindex.phpにアクセスさせる・・・らしい。
違ったらごめんなさい。

index.php

<?php
    $path = explode("/",$_SERVER["PATH_INFO"]);
?>

これで現在のURLのディレクトリを配列で取得出来る。
https://example.com/test/hello/bayにアクセスしている場合
$pathの中は
Array ( [0] => [1] => test [2] => hello [3] => bay )
となっている。

show/main.html

こちらはコンテンツです。

ブラウザに表示する文字を書きます。
ではURLがhttps://example.com/contentsの時、show/main.htmlを表示させてみる。

コードを追加

index.php

<?php
    $path = explode("/",$_SERVER["PATH_INFO"]);
    switch($path[1]) {
        case "contents": include "show/main.html"; break;
    }
?>

https://example.com/contentsにアクセスすると
こちらはコンテンツです。と表示されます。

$path[1]がcontentsなら、つまりURLのディレクトリの1番目がcontentsならshow/main.htmlをincludeします。
なのでhttps://example.com/contents/helloでもshow/main.htmlがincludeされブラウザにこちらはコンテンツです。と表示されます。

https://example.com/contents/helloの場合表示させない

index.php

<?php
    $path = explode("/",$_SERVER["PATH_INFO"]);

    switch($path[2]) {
        default: exit();
    }

    switch($path[1]) {
        case "contents": include "show/main.html"; break;       
    }
?>

上記の場合はURLのディレクトリが2階層以上の場合exit()により処理が止まります。
if($path[1] === "contents") {}などでいろいろ条件分岐出来ると思います。

おまけ

ルートのindex.phpで動かしてるのでshow/main.htmlに書いたPHPのコードも動きます。

フレームワークを使わずに以下のルーティングを使って自作したサイトたち

自作SNS
https://test.nieru.net/
ユーザーページサンプル
https://test.nieru.net/admin
https://test.nieru.net/nieru
(利用者募集しております。)

無料レンタル掲示板サイト
https://nieru.net/
掲示板活用サンプル
- https://nieru.net/sample
- https://nieru.net/vip
- https://nieru.net/atbs

2
7
2

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
7