1
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 3 years have passed since last update.

URLの一部をパラメータとして扱うには

Last updated at Posted at 2021-05-01

やりたいこと

  • URLの一部をパラメータとして扱いたい
  • 仮想的にURLとして扱いたい

こんな感じで
https://blog.tanukey.com/date/2021-04-30
https://blog.tanukey.com/single/2021-04-30/1
URLのうち、
「/date/2021-04-30」「/single/2021-04-30/1」
をパラメータと扱い実態は存在しない(架空のパス)。

処理イメージ

  1. どのようなリクエストを受けても、URLをそのままに特定のファイル(例:index.php)リダイレクトする。(リダイレクトしても、リクエストのURLは保持されます)
  2. リダイレクトされたファイルは、リクエストを解析しDB処理などを行う。
  3. 適切なレスポンスを返す。
    o.png

方法

リクエストを一か所(index.php)に集める

Apache をお使いの場合

.htaccessファイルを作成し、下記コードを記載する。

[.htaccess]
RewriteEngine On # 設定の書き換えを有効にします。
RewriteBase / # ディレクトリごとの書き換えのベースURLを設定します
RewriteRule ^index\.php$ - [L] # 正規表現で一致した場合、置換せずに処理を停止します。すなわち、index.php の場合は何もしない。
RewriteCond %{REQUEST_FILENAME} !-f # リクエストがファイルでない場合
RewriteCond %{REQUEST_FILENAME} !-d # リクエストがディレクトリでない場合
RewriteRule . /index.php [L] # すべてのリクエストをindex.phpにする

IIS をお使いの場合

web.configファイルを作成し、下記コードを記載する。

web.config
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Imported Rule 1" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php" appendQueryString="true" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

index.php でリクエストを取得して処理する

index.php
<?php
  $request = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
  # ここで $request を処理して、レスポンスを返す。
?>

$request からパラメータを取得し、パラメータをキーにDBから情報を取得するなどの処理をした結果をレスポンスとして返すことができます。

参考サイト

1
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
1
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?