.htaccessファイルを介してURL書き換えルールを追加しようとしている静的HTMLサイトがあります。
サイトファイルディレクトリは次のようになります。
- index.htm
- about-us [subdirectory]
- index.htm
- careers [subdirectory]
- index.htm
- contact [subdirectory]
- index.htm
- map.htm
- privacy.htm
- projects [subdirectory]
- index.htm
- education.htm
- healthcare.htm
- recreation.htm
- residential.htm
- hospitality.htm
- services [subdirectory]
- index.htm
私の目標は、ページのURLからファイル拡張子を削除し、末尾にスラッシュを追加し、301リダイレクトを強制して、ファイルに元の形式(https://example.com/projects/education.htm)でアクセスしようとする人がいるようにすることです。)は、よりクリーンな形式(https://example.com/projects/education/など)に自動的に書き換えられます。
私のサイトのルートにある.htaccessファイルでindex.htmファイルをすでに書き換え/リダイレクトしています。これが私がこれまでに持っているものです:
DirectoryIndex index.php index.html index.htm
RewriteEngine On
RewriteCond %{REQUEST_URI} (.*)/$
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.htm -f
RewriteRule ^(.+)/$ /$1/ [R=301,L]
RewriteRule ^index\.htm$ / [R=301,L]
RewriteRule ^(.*)/index\.htm$ /$1/ [R=301,L]
ディレクトリルートファイル(index.htm)をURLから正常に削除しましたが、私の人生では、ルート以外のファイル(つまり、education.htm)を目的の形式に書き換えることができないようです。
誰かが私が間違っていることに光を当てることができますか?
更新
@misorudeのコメントによると、最初の書き換えルールを削除しました。また、301を302に変更しました(少なくとも一時的に、ルールのキャッシュの問題を回避するため)。また、既存のルールを変更して、正規表現の「+」文字を使用して、ルールに実際のファイル名またはフォルダー名を強制しました。
最後に、新しい3番目のルールを追加しました。これは、すべてのサブディレクトリの「インデックス以外の」ページを検索し、それらのファイル拡張子を削除する試みです。これは機能しているようです。ただし、これらの非インデックスページで404エラーが発生します。
以前に機能していたindex.htm書き換えルールはすべて正常に機能していますが、インデックス以外のルールでは404エラーがスローされます。これが私のアップデートhtaccessファイルです:
DirectoryIndex index.php index.html index.htm
RewriteEngine On
RewriteCond %{REQUEST_URI} (.*)/$
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.htm -f
# If we're on the root index page of the site,
# remove index.htm from URL
RewriteRule ^index\.htm$ / [R=302,L]
# If we're on a subdirectory index page, remove the index.htm from the URL
RewriteRule ^(.+)/index\.htm$ /$1/ [R=302,L]
# If we're on a non-index page of a subdirectory,
# remove the extension from the URL
RewriteRule ^(.+)/(.+)\.htm$ /$1/$2/ [R=302,L]
何かアドバイス?
MultiViews
オプションを無効にして各ケースを処理することによる完全なソリューションは次のとおりです
DirectoryIndex index.php index.html index.htm
Options -MultiViews
RewriteEngine On
# redirect "/index.htm" or "/xxx/index.htm" to "/" or "/xxx/"
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{THE_REQUEST} \s/([^/]+/)?index\.htm\s [NC]
RewriteRule ^ /%1 [R=302,L]
# redirect "/xxx/page.htm" to "/xxx/page/"
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{THE_REQUEST} \s/([^/]+)/([^/]+)\.htm\s [NC]
RewriteRule ^ /%1/%2/ [R=302,L]
# rewrite back "/xxx/page/" to "/xxx/page.htm"
RewriteCond %{DOCUMENT_ROOT}/$1/$2\.htm -f
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.htm [L]
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加