Monday, June 11, 2012

Disable PHP in directory (including all sub-directories) with .htaccess

I'm making a website which allows people to upload files, html pages, etc... Now I'm having a problem. I have a directory structure like this:

-/etc... (every user has his own direcory here)

Now I want to disable PHP, but enable Server-side includes in the direcories and subdirectories inside /USERS

Can this be done (and how :) )? Thanks in advance.

BTW, I use WAMP server

Source: Tips4all


  1. Try to disable the engine option in your .htaccess file:

    php_flag engine off

  2. To disable all access to sub dirs (safest) use:

    <Directory full-path-to/USERS>
    Order Deny,Allow
    Deny from All

    If you want to block only PHP files from being served directly, then do:

    1 - Make sure you know what file extensions the server recognizes as PHP (and dont' allow people to override in htaccess). One of my servers is set to:

    # Example of existing recognized extenstions:
    AddType application/x-httpd-php .php .phtml .php3

    2 - Based on the extensions add a Regular Expression to FilesMatch (or LocationMatch)

    <Directory full-path-to/USERS>
    <FilesMatch "\.(php3?|phtml)$">
    Order Deny,Allow
    Deny from All

    Or use Location to match php files (I prefer the above files approach)

    <LocationMatch "/USERS/.*\.(php3?|phtml)$">
    Order Deny,Allow
    Deny from All

  3. If you're using mod_php, you could put (either in a .htaccess in /USERS or in your httpd.conf for the USERS directory)

    RemoveHandler .php


    RemoveType .php

    (depending on whether PHP is enabled using AddHandler or AddType)

    PHP files run from another directory will be still able to include files in /USERS (assuming that there is no open_basedir restriction), because this does not go through Apache. If a php file is accessed using apache it will be serverd as plain text.


    Lance Rushing's solution of just denying access to the files is probably better

  4. This might be overkill - but be careful doing anything which relies on the extension of PHP files being .php - what if someone comes along later and adds handlers for .php4 or even .html so they're handled by PHP. You might be better off serving files out of those directories from a different instance of Apache or something, which only serves static content.

  5. This will display the source code instead of executing it:

    <VirtualHost *>
    DocumentRoot /var/www/example
    AddType text/plain php

    I used it to enable other co-workers to have read access to the source code (just a quick alternative).

  6. Order Deny,Allow
    Deny from All

    doesn't work, now the pics in that directory are not shown.