0

This is what I currently have as my htaccess file...

setEnv HTTP_TARGET_PAGE %{REQUEST_FILENAME}
ErrorDocument 404 default
ErrorDocument 301 default
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

#the below line doesn't work
RewriteCond %{REQUEST_URI} *.php
#the above line doesn't work

RewriteRule ^.*$ ./index.php

I'm trying to have every php file or nonexistant file request pipe through index.php for processing. All the other php files are things sometimes included in index.php (using web address).

So I may have somewhere in my index.php

if($my_url = "www.example.com/potato"){
    require_once("potato.php");
}

But I dont' want them typing in "http://www.example.com/potato.php" and getting the php directly without headers and such. My htaccess isn't working right (that one line borks it every time). But I don't want to rewrite everything because image files would then not work. How do I address it?

lilHar
  • 1,735
  • 3
  • 21
  • 35
  • To Popnoodles, 3dgoo, Milap, Alex Tartan, and un-lucky... Different question with different solution. The solution you linked to rewrites everything. I was *only* trying to rewrite .php requests and unfound files, the one you link to rewrites practically everything. – lilHar Mar 10 '16 at 17:03

1 Answers1

1

Not quite sure I understand your requirement but I think this is what you want.

RewriteEngine on

#don't do anything if index.php is called directly
RewriteRule ^index\.php - [L]
#if other php file called(user typed it in), redirect to extensionless uri
RewriteCond %{THE_REQUEST} ^GET\ /(.+)\.php
RewriteRule ^ /%1? [R=302,L]    
#if extensionless uri maps to a real php file, forward to index.php
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [OR]
#or if not a real file or directory forward to index.php
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.+)/?$ /index.php [L,NC]
Panama Jack
  • 24,158
  • 10
  • 63
  • 95
  • That worked well, thankyou! I saw a couple lines in there I didn't understand though (such as ^ /%1? [R=302,L]), and I prefer to understand my code (and I've been trying to understand htaccess and mod_rewrite for awhile now). Any resources you'd suggest? – lilHar Mar 10 '16 at 16:41
  • 1
    @liljoshu when you use a group match in a condition `/(.+)\.php` the back reference becomes `%1` which is being captured by `(.+)` So the rewrite rule will redirect with a 302 to that location. It can be difficult to understand at first, it just takes time. Honestly the whole [rewrite doc](http://httpd.apache.org/docs/current/mod/mod_rewrite.html) is a good place to start. Then get familiar with regex and it'll come together. – Panama Jack Mar 10 '16 at 21:15