Home > Software design >  Remove php extension for only one file by using htaccess
Remove php extension for only one file by using htaccess

Time:05-24

I am learning how to configure htaccess. Today, I wanted to hide the PHP access when opening a certain PHP page without removing the extension from the file.

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php

This code works, but it removes the PHP extension for all PHP files. How can I restrict it to only one file? Suppose the path is: https://example.com/content/myfile.php

And, if I want to add another file in the future, for example, https://example.com/content/otherfile.php, how can I do it without writing the same rule twice? Thanks!

CodePudding user response:

with the code I just posted I can visit example.com/content/myfile correctly. But I wanted to restrict it to only this URL.

RewriteRule ^content/myfile$ content/myfile.php [L]

Or, use a backreference to save repetition:

RewriteRule ^content/myfile$ $0.php [L]

The $0 backreference contains the URL-path matched by the RewriteRule pattern (ie. "content/myfile").


RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php

This code works, but it removes the PHP extension for all PHP files.

(As stated in comments, this does not actually "remove" anything.)

But this only applies to requests that exist as physical files when the .php extension is applied, so if you don't want it to apply then you shouldn't be requesting the arbitrary URL without the .php extension in the first place. (?)

And, if I want to add another file in the future, for example, https://example.com/content/otherfile.php, how can I do it without writing the same rule twice?

If you only want this to apply to a second arbitrary file then you obviously need to write essentially the same rule twice (or modify the existing rule), otherwise, how does Apache know to rewrite the URL (without writing a more generic rule that you had initially)?

You could combine/simplify the two rules into one, but this is not necessarily an improvement. For example, the following single rule will rewrite both URLs:

RewriteRule ^content/(myfile|otherfile)$ $0.php [L]

But this is really the purpose of the first rule you posted - so you don't need to write a second rule (or update your .htaccess file each time) for each URL.

  • Related