Home >Backend Development >PHP Tutorial >How to Hide PHP Extension in .htaccess: A Comprehensive Guide?

How to Hide PHP Extension in .htaccess: A Comprehensive Guide?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-06 22:16:02249browse

How to Hide PHP Extension in .htaccess: A Comprehensive Guide?

Hiding .php Extension in .htaccess: A Comprehensive Solution

In web development, it's often desirable to hide the .php file extension to enhance the URL's aesthetic appeal and prevent malicious activity. However, achieving this can sometimes pose a challenge.

Implementing the Solution

To effectively hide the .php extension using .htaccess, consider the following code:

RewriteEngine On

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://example.com/folder/ [R=301,L]

# Redirect external .php requests to extensionless URL
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://example.com/folder/ [R=301,L]

# Resolve .php file for extensionless PHP URLs
RewriteRule ^([^/.]+)$ .php [L]

Explanation

  • Line 1 enables the .htaccess rewrite engine.
  • Lines 3-6 remove any trailing slash if the request is not a directory.
  • Lines 8-11 redirect external .php requests to equivalent extensionless URLs.
  • Lines 13-15 resolve .php files for extensionless PHP URLs.

The above is the detailed content of How to Hide PHP Extension in .htaccess: A Comprehensive Guide?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn