LoginSignup
19
21

More than 5 years have passed since last update.

Apacheのmod_rewrite設定メモ

Posted at

この記事でわかること

dockerにて、Apacheのmod_rewriteの設定を行い、リクエストするURLをスマートにする方法。

どんなURLを指定されても、index.phpを介してコントローラへ処理を引き渡すようにする方法。

経緯

REST APIを試そうとしたが、URLの指定方法が気に入らなかった。
処理hogeを呼び出すとき、以下のようにURLを指定させたかった。

やめたかったURL表記
https://localhost/api.php?action=hoge

やりたかったURL表記
https://localhost/api/hoge

解決策

1.モジュールを入れる

debian系OSが元になっているDocker Imageの場合、このコマンドでrewriteモジュールを有効化する必要があるそうです。
a2enmod rewrite

2.apache設定ファイルを編集

/etc/apache2/sites-available/000-default.confを編集。
以下を<VirtualHost></VirtualHost>内に追加。

000-default.conf
    <Directory /var/www/html>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
    </Directory>

3..htaccessを編集

/var/www/html.htaccessを編集します。(なければ作成します。)

.htaccess
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^api/(.*)$ index.php
</IfModule>

この設定をすることで、https://localhost/api/で始まるURLで指定されたリクエストは、すべてindex.phpを実行するようになりました。
あとは、index.phpで、$_SERVER['REQUEST_URI']でとってきたURL情報を/で区切るなりなんなりし、パラメータとして取り出せばいいのかな。
(この方法を使うと$_SERVER['PATH_INFO']は使えなくなるらしい。)

その他

Dockerで行う場合は、Dockerfileにコマンドを記述するなり、設定ファイルをビルド時に配置させたりして何とかする。

参考

19
21
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
19
21