0

Possible Duplicate:
remove .php extension with .htaccess

I know little about .htaccess, What I'm trying to accomplish is two-fold.

  1. Allow requests to .php to be called with or without the .php and with or without a trailing slash. For example.

    /profile.php works
    /profile appends .php, works
    /profile/ append .php so it works

  2. If the file or directory doesn't exist after trying the above, then treat as a 404 and redirect to another page.

    /something failure, redirect to /404.php?id=$1 (url requested)

I have two rules that work separately, but I need to conditionalize these or something. Any advice would be appreciated.

RewriteEngine on

# This works for the PHP part.
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)/?$ $1.php

# This works for general 404 handling
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /404.php?url=http://%{HTTP_HOST}/$1 [L]
Community
  • 1
  • 1
dpluscc
  • 590
  • 1
  • 8
  • 18
  • 1
    Alternatively, there is `Options +MultiViews` or `ErrorDocument 404` for accomplishing the same. Where did you find the first half? (That's where the problem lies.) – mario Jan 22 '13 at 22:21
  • why do you need to `conditionalize these or something`? – Peter Jan 22 '13 at 22:22
  • The "conditionalize" is just my way of saying I really only need one of these to run at a time. They both operate on "non-existent" files. If the first set actually finds a .php, then that should be the end of it. If it doesn't, then it should take those 404s and push to 404.php. Mario - not sure how this is a duplicate. I don't see the combination of these two objectives in the answers, but I could be wrong. – dpluscc Jan 22 '13 at 22:28
  • Not sure how to mark a comment as answered, but Multiviews was the answer. I turned that on, and commented out the first rewriterule and it works like I want. Thanks! – dpluscc Jan 22 '13 at 22:35

1 Answers1

1

Apache will automatically append .php to /profile and /profile/ without any mod_rewrite. The only thing you should handle is the 404 page.

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /404.php?url=http://%{HTTP_HOST}/$1 [L]

However, if it's not working for some reason (e.g. apache wasn't configured well):

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/?$ $1.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /404.php?url=http://%{HTTP_HOST}/$1 [L]
n1xx1
  • 1,971
  • 20
  • 26