htaccess redirect any urls ending in .php to index

2019-09-03 19:29发布

I've set up my .htaccess so far as follows:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?page=$1 [QSA]

My index.php loads the file from /pages, eg. index.php?page=home will load the page content from pages/home.php

However - if someone went to pages/home.php the page loads without the headers etc. which is undesirable. What can I add to redirect any URLs ending in .php to just take the user to the homepage?

Thanks

2条回答
Fickle 薄情
2楼-- · 2019-09-03 19:57

This should redirect pages/anything.php to index.php?page=anything:

RewriteCond %{REQUEST_URI} \.php$
RewriteRule ^(.*/)?([^/]*)\.php$ /index.php?page=$2 [R=301,L]

note the security tips above. include injection is bad..

查看更多
叛逆
3楼-- · 2019-09-03 20:09

A separate RewriteRule (without file exists condition) for ^(.*)\.php$ should work. But why are people trying to access the .php directly? If there isn't a good reason, a Deny in the directory is probably a better bet.

(And, as @Col. Shrapnel comments, beware include injection. I hope you're filtering your page names well.)

edit: include injection: Consider what happens if someone gives you an interesting page name, such as page=http://foo.com/exploit, will your script run it? What about page=/etc/passwd or page=/../../../etc/passwd, will you print out the password file? page=`mysqldump …`, will you give a copy of your database?

查看更多
登录 后发表回答