.htaccessを使用して、ドメインをサブディレクトリにリダイレクトさせる

Last Updated:2023年07月16日| | コメントを残す

.htaccessを使用して、メインドメインのURLをサブディレクトリにリダイレクトすることができます。

例えば、 WordPress(WordPress)をサブディレクトリにインストールした場合、メインドメインのアドレスを入力すると、 WordPressがインストールされてサブディレクトリに移動させるときに使用することができます。 (WordPressの場合、この方法より」WordPress アドレスの変更にサイトにアクセスしていない問題の解決「文から」WordPress サイトのアドレスをサブフォルダからルートに変更する」を参照してください。

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www.)?YourDomain.com$
RewriteRule ^(/)?$ blog [L]
# Source: site5 Blog

YourDomain.comをドメインのメインアドレスに置き換えて、 blogを実際のサブディレクトリに置き換えます。

RewriteEngine On

# Map http://www.YourDomain.com /blog.
RewriteRule ^$ /blog/ [L]

# Map http://www.YourDomain.com/x to /blog/x unless there is a x in the web root.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/blog/
RewriteRule ^(.*)$ /blog/$1

# Add trailing slash to directories within blog
# This does not expose the internal URL.
RewriteCond %{SCRIPT_FILENAME} -d
RewriteRule ^blog/(.*[^/])$ http://www.YourDomain.com/$1/ [R=301]
# Source: stackoverflow

同様に、メインドメインのURLを入力すると/blog サブディレクトリに自動的に移動します。

# .htaccess main domain to subdirectory 'blog' redirect
# Do not change this line.
RewriteEngine on
# Change YourDomain.com to be your main domain.
RewriteCond %{HTTP_HOST} ^(www.)?YourDomain.com$
# Change 'blog' to be the directory you will use for your main domain.
RewriteCond %{REQUEST_URI} !^/blog/
# Don't change the following two lines.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Change 'blog' to be the directory you will use for your main domain.
RewriteRule ^(.*)$ /blog/$1
# Change YourDomain.com to be your main domain again.
# Change 'blog' to be the directory you will use for your main domain
# followed by / then the main file for your site, index.php, index.html, etc.
RewriteCond %{HTTP_HOST} ^(www.)?YourDomain.com$
#RewriteRule ^(/)?$ blog/index.html [L]
## index.php for WordPress
RewriteRule ^(/)?$ blog/index.php [L]
# Source: stackexchange

便宜上、メインドメインアドレスはYourDomain.comで、サブディレクトリは blogと統一しました。 このコードは各行に詳細な説明があり、コードをよりよく理解することができます。 このコードを適用すると、www.example.com/blog/abcの代わりにwww.example.com/abc形式でサブディレクトリなしで入力しても正常に動作します。 つまり、この場合はブラウザのURLにサブディレクトリ(blog) が表示されずに正常にページが表示されます。 (WordPressをサブフォルダにインストールしたときに、この方法を利用すれば、あえて この記事に説明された方法に従わなくても、サブディレクトリを効果的に非表示にすることができます。)

メモ:


コメントを残す

コメント