TroodoN-Mike
TroodoN-Mike

Reputation: 16165

How to work with subfolders in RewriteRule

I am trying to make this rewrite rule to work. What i want is (incoming url):

http://hostname.com/mywebsite

http://hostname.com/mywebsite/test

http://hostname.com/mywebsite/something/another

to (behind the scene):

http://hostname.com/app.php

http://hostname.com/app.php/test

http://hostname.com/app.php/something/another

The common thing is "mywebsite" that needs to be ignored but url still shows it

Below rewrite rule does not work so please help

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^mywebsite(.*) /app.php/$1 [QSA,L]

Any help would be really good. Thanks!

Upvotes: 1

Views: 176

Answers (1)

rajukoyilandy
rajukoyilandy

Reputation: 5471

I think a more reliable and pretty simple solution is as follows:

Consider the two cases:

Case 1: If you want a full URL redirection use the following Rewrite Rule

RewriteEngine On
#Redirect to app.php/the-rest-of-param
RewriteRule ^mywebsite(.*)$ http://%{HTTP_HOST}/app.php$1 [R=301,L]

Note that URL will be changed as follows

http://hostname.com/mywebsite to http://hostname.com/app.php

http://hostname.com/mywebsite/test to http://hostname.com/app.php/test

http://hostname.com/mywebsite/something/another to http://hostname.com/app.php/something/another

Case 2: If you do not want a full redirection (ie., URL should not be changed), then you need to consider below points.

  1. In this case requested URL will be preserved (ie., url should be something like http://hostname.com/mywebsite/test)
  2. As end user should not be aware of whats going inside, then you do not need to bypass your request to app.php/test and thus no server overhead, and instead bypass your request to app.php (I'll explain the rest with PHP code below)

Simply use below rule

RewriteEngine On
#No redirection, bypass request to app.php
RewriteRule ^mywebsite(.*)$ app.php

Now you need to get parameters like /test and /something/another right? grab it using following code block.

$param = '';
if (strpos($_SERVER['REQUEST_URI'], '/mywebsite') === 0) {
    //10 => length of "/mywebsite"
    $param = substr($_SERVER['REQUEST_URI'], 10);
}

echo 'URL PARAM: ' . $param;

For the URL http://hostname.com/mywebsite $param will be empty string

and for http://hostname.com/mywebsite/test $param will be /test

and for http://hostname.com/mywebsite/something/another/1234 $param will be /something/another/1234

Note that I've just avoided unwanted conditional request-bypasses, and just bypassed all requests to app.php without any parameters (since parameters are there along with URL)

You can see $_SERVER['REQUEST_URI'] will hold value something like /something/another/1234 and $_SERVER['PHP_SELF'] will be similar to /app.php/something/another/1234

Hope this can solve your problem...

Upvotes: 1

Related Questions