Home > Backend Development > PHP Tutorial > Why Can't I Hide My .php File Extension with .htaccess?

Why Can't I Hide My .php File Extension with .htaccess?

Mary-Kate Olsen
Release: 2024-11-06 18:08:02
Original
428 people have browsed it

Why Can't I Hide My .php File Extension with .htaccess?

Hiding .php File Extension with .htaccess: Troubleshooting Tips

Despite following instructions to conceal the .php file extension using .htaccess, you're encountering difficulties. Let's investigate the issue and provide a revised solution.

Your initial .htaccess code attempted to rewrite URLs within a specific "folder" directory. However, it appears incomplete, as it lacks the corresponding RewriteCond directive. To address this, the following modified code should work:

<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteRule ^folder/([a-zA-Z_\-0-9]+)/?$ /folder/.php
</IfModule>
Copy after login

The RewriteCond line ensures that the rule is only applied if the requested file doesn't exist (i.e., it's not a static file).

In addition, to handle various scenarios properly, consider using a more comprehensive .htaccess code like the one suggested in the accepted answer:

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]
Copy after login

This code not only hides the .php extension but also handles trailing slashes, external .php requests, and internally resolves .php files for extensionless URLs.

Remember, verify that the .htaccess file is placed in your project's root directory and check the file's permissions to ensure it's readable by the web server.

The above is the detailed content of Why Can't I Hide My .php File Extension with .htaccess?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template