简体   繁体   中英

remove and disallow extensions with .htaccess

I found this script or removing extensions from php files:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

While this works, it still allows files to be accessed if you type them in with their extension, which I don't want.

I tried the following:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([.]+)$ $1.php [NC,L]

I also tried ^(.*)$ and ^(.+)$

which seems like it should do the job, because it would do this:

index.php -> index.php.php

but somehow, it doesn't work as expected.

So how do I update the above .htaccess script to disallow file extensions?

EDIT:

My .htaccess script seems to be detecting the files correctly:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule "^.*\.php$" "other.html" [L]
RewriteRule "^([^\.]+)$" "other2.html" [L]

The pages other.html and other2.html simply contain the words "OTHER" and "OTHER 2"

Now, using the above script, the output is as expected:

"/test.php" gives output "OTHER"
"/test" gives "OTHER 2"

but if I update the script to the following, both url variations start returning "OTHER"

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule "^.*\.php$" "other.html" [L]
RewriteRule "^([^\.]+)$" "$1.php" [L]      // changed

So it seems that after the extensionless filename has ".php" added to it by rule#2, it somehow gets caught by rule #1.

Aren't these rules ordered? and isn't [L] supposed to stop processing on a match?

EDIT 2:
So assuming [L] did what I was expecting... the following script would work...

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule "^.*\.php$" "404.html" [L]
RewriteRule "^([^\.]+)$" "$1.php" [L]

Try this solution How to remove file extension from website address?

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

edit: you can do a filematch to prevent executing all .php except index.php. I typically route most of my pages through index.php anyways so this solution would work if you only have a handful of base index files (index1.php,index2.php,etc). I'm sure you can come up with something from this if you don't find a working solution.

<FilesMatch "\.php$">
    Order Allow,Deny
    Deny from all
</FilesMatch>
<FilesMatch "index[0-9]?\.php$">
    Order Allow,Deny
    Allow from all
</FilesMatch>

This works:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule "^.*\.php$" "404.html" [END]
RewriteRule "^([^\.]+)$" "$1.php" [END]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM