skip to Main Content

The .htaccess file below in my root directory serves to rewrite all /api/ then outputs the key value pairs from the URL from the $_GET inside /api/api.php?

How do I modify this so that all existing files or folders inside api (such as /api/test or /api/test/file.php accessed via this scheme will not rewrite via the rewrite rule?

<IfModule mod_rewrite.c> 
    Options +FollowSymlinks
    RewriteEngine On
    RewriteCond %{REQUEST_URI} ^/api
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    #RewriteRule (.*) $1
    RewriteCond %{QUERY_STRING} ^(.*)$
    RewriteRule ^(.*/)([^/]+)/([^/]+) $1?$2=$3&%1 [QSA,L]
    RewriteCond %{REQUEST_URI} ^/api
    RewriteCond %{QUERY_STRING} ^(.*)$
    RewriteRule ^([^/]+)/ $1/$1.php?%1 [L]
</IfModule>

2

Answers


  1. Chosen as BEST ANSWER

    I made the following .htaccess file to include Directory index and fallback resource and placed it inside the the root directory to catch on each request from the root.

    Also I put the rewritebase /api and InheritDown option to limit where I apply these rules and also recursively propagate down to directories that exist already so they (and nested files) will not get included in the rewrite process when requested.

    This produced a successful result on $_GET where there were equal numbers of lhs (key) = rhs (value) pairs in the query string provided that they were entered as /api/lhs/rhs/lhs/rhs in in the request.

     <IfModule mod_rewrite.c> 
        Options +FollowSymlinks
        RewriteEngine On
        DirectoryIndex api.php
        FallbackResource index.php
        RewriteCond %{REQUEST_URI} ^/api
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_URI} ^/api
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{QUERY_STRING} ^(.*)$
        RewriteRule ^(.*/)([^/]+)/([^/]+) $1?$2=$3&%1 [QSA,L]
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{QUERY_STRING} ^(.*)$
        RewriteRule ^([^/]+)/ $1/$1.php?%1 [L]
    </IfModule>
    
    RewriteBase /api
    RewriteOptions InheritDown
    

  2. You can use RewriteCond directive to exclude your files and folders

    RewriteEngine On
    #if not a file
    RewriteCond %{REQUEST_FILENAME} !-f
    #not a directory
    RewriteCond %{REQUEST_FILENAME} !-d
    #rewrite the /api request
    RewriteCond %{REQUEST_URI} ^/api
    RewriteCond %{QUERY_STRING} ^(.*)$
    RewriteRule ^([^/]+)/ $1/$1.php?%1 [L]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search