skip to Main Content

i’m designing a mvc application in php and I want to reformat and parse the url. My folders are as below:

  • App
  • Public
    • Assets
    • .htaccess

my htaccess file includes:

 Options -Multiviews 
RewriteEngine On 
RewriteBase /mymvctest/public 
RewriteRule ^(.*)/$ index.php?url=$1 [END,QSA] 
RewriteRule ^(.*)$ index.php?url=$1 [END,QSA]

Index.php receives a "url" GET variable and prints it for the sake of this example.

if my input url is /mymvctest/public/atestvalue the final url will be the same,/mymvctest/public/atestvalue, and "atestvalue" will be printed in index too.

but when my input url includes a valid directory, the query is shown in the url. for example, if my url is /mymvctest/public/Assets the final url will be /mymvctest/Public/Assets/?url=Assets. The surprising part is that when i add a slash after "Assets", /mymvctest/public/Assets/, the final url will be be the same as my input url: /mymvctest/public/Assets/. I get the "url" variable in both cases though.

why is this happening!?

2

Answers


  1. Look at the 2nd and 3rd lines.

    RewriteEngine On 
    #if not a file
    RewriteCond %{REQUEST_FILENAME} !-f 
    #if not a directory
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteRule ^(.*)$ index.php?url=$1 [END,QSA]
    

    Input Url :

    http://localhost/mymvctest/public/testvalue

    http://localhost/mymvctest/public/Assets/

    Output Url :

    http://localhost/mymvctest/public/index.php?url=testvalue

    http://localhost/mymvctest/public/Assets/

    Login or Signup to reply.
  2. It is happening this way because /mymvctest/public/Assets is an actual directory. First mod_rewrite rule executes and makes it /mymvctest/public/index.php?url=Assets internally.

    Apache has another module called mod_dir that (due to security reasons) catches all original URLs that point to a directory and have a missing trailing slash. It then redirects them to same path with a trailing slash with R=301 thus making final URL as: /mymvctest/public/Assets/?url=Assets.

    In other to prevent this behaviour, use

    DirectorySlash off
    

    However this might expose your directory content in browser. To prevent that use this directive as well:

    Options -Indexes
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search