実際のファイルの.phpを削除せずにphp拡張子を非表示にする[重複]

Mar 22 2020

これは、htacessを使用してphp拡張子を非表示にする最も一般的な方法ですが、これは実際のファイルに拡張子がない場合にのみ機能します。たとえば、このようなファイルindex.phpindexこれに変更する必要がある場合、開発モードには適していません。拡張子を非表示にして、ファイル名をそのまま維持するには?

  # Run Php without filename extension
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php

# Return 404 if original request is .php
RewriteCond %{THE_REQUEST} "^[^ ]* .*?\.php[? ].*$"
RewriteRule .* - [L,R=404]

これが私のファイル構造です

私のウェブサイト[ルートフォルダ]

  • index.php
  • about.php

ビューフォルダ[ルート内]

  • index.php
  • about.php

回答

LSerni Mar 22 2020 at 19:33

あなたが投稿する方法は、あなたが望むことを正確に行います。ファイルシステムに「index.php」ファイルがあり、URLは「www.mysite.com/index」のようなものです(URLに.php拡張子はありません)。

RewriteEngine on
# The requested filename "/index" is not a directory
RewriteCond %{REQUEST_FILENAME} !-d
# There is a file on the file system named as the request, with extension .php
RewriteCond %{REQUEST_FILENAME}.php -f
# If all of the above is true, pretend that the ".php" file had been called
# by rewriting the request appending .php
RewriteRule ^(.*)$ $1.php

「index.php」の名前を「index」に変更する必要はありません。

.phpが指定されている場合にアクセスを防止したい場合は、このルールを上記のルールの前に配置してください。これで、「mysite / index」は機能しますが、「mysite /index.php」は機能しません。

# Return 404 if original request is .php
RewriteCond %{REQUEST_FILENAME} "\.php$"
RewriteRule .* - [L,R=404]

あなたのサイトがPHPを使用していることに誰かが気付く方法は他にもいくつかあり、php-to-404ルールはあまり意味がないことに注意してください。