Question

I have following directory structure on my local LAMP:

  • www
    • basic
      • app
        • router.php
      • public
        • index.html
        • .htaccess

and i can access my index page with localhost/basic/public/ and i am not using any virtual hosts.

Now i am trying to do two things:

1: instead of localhost/basic/public/ URL should look like localhost/basic/ to access homepage.

2: all requests to /api/ should be redirected to router.php. For example if I make a request like /api/user/login it should go to app/router.php where i can execute specific code according to request for api.

To achieve this i was trying do something like following in .htaccess file but its not working:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^/api/ [NC]
RewriteRule . ../app/router.php [NC,L]

Also i am not sure if we can use relative paths in RewriteRule.

Was it helpful?

Solution

To summarize, you want:

  • There is a special case: If an url starts with /basic/api, you want it to go to the router.php page
  • By default, an url that isn't a file should be searched for in public.

In addition you can redirect requests that go to /basic/public/something to /basic/something


Put this in a file .htaccess in the basic folder:

RewriteEngine On
RewriteBase /preview/

#Special case: api requests
RewriteRule ^api/ app/router.php [L]

#Default case: all public files
#Alternativelly use RewriteCond %{REQUEST_URI} !/basic/public
RewriteCond %{REQUEST_URI} !/public/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ public/$1 [L]

#Optionally prevent both localhost/basic/public/file and localhost/basic/file
#outputting the same
#Using THE_REQUEST trick to only match external requests
RewriteCond %{THE_REQUEST} ^(POST|GET)\ /basic/public/
RewriteRule ^public/(.*)$ $1 [R,L]

This will do the following:

localhost/basic/api/user/something gets internally rewritten to localhost/basic/app/router.php

localhost/basic/something gets internally rewritten to localhost/basic/public/something

localhost/basic/public/something gets externally redirected to localhost/basic/something (and is then internally rewritten)

Screencast of behaviour: http://www.screenr.com/9GUN

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top