.htaccessを記述して、作成されたサブフォルダー内のすべてのリクエストをindex.phpに転送する方法

May 28 2020

すべてのリクエストをindex.phpに転送したいのですが、リクエストが行われたサブフォルダーを尊重します。すべてをルートindex.phpに移動させることはできますが、特定のサブフォルダーのindex.phpに移動させることはできません。

例:
site.com/testurl > site.com/index.php
site.com/admin/testurl > site.com/admin/index.php
site.com/randomname/randomname > site.com/randomname/index.php

サブフォルダーをハードコーディングして、動的な状態を維持したくありません。

現在、私はこれを.htaccessファイルとして持っています:

DirectoryIndex index.php

# enable apache rewrite engine
RewriteEngine on

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1%{REQUEST_URI} [R=301,QSA,NC,L] # Deliver the folder or file directly if it exists on the server RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Push every request to index.php RewriteRule ^(.*)$ index.php [QSA]

追加のクレジット(これが.htaccessで可能かどうかはわかりません):index.phpがサブディレクトリにあるかどうかを認識し、存在しない場合はルートindex.phpにフォールバックするようにします。

回答

1 kmoser May 28 2020 at 11:40
# Determines whether the request doesn't end with index.php:
RewriteCond %{REQUEST_URI} !/index.php$ # Redirect to the requested path, followed by index.php: RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)/(.*)$    /$1/index.php [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !/index.php$
RewriteRule ^(.*) /index.php [L]