htaccess rewrite index.php on root and subfolders

2019-04-15 23:56发布

问题:

I'm trying to redirect all requests to ./index.php?site=$1 while I only want to use the part behind the last slash.

So I want www.mydomain.com/firstpage to become www.mydomain.com/index.php?site=firstpage and www.mydomain.com/subfolder/anotherpage to become www.mydomain.com/subfolder/index.php?site=anotherpage

But right now www.mydomain.com/subfolder/anotherpage becomes www.mydomain.com/index.php?site=subfolder/anotherpage

This is what I've got:

RewriteEngine on
Options +SymlinksIfOwnerMatch
RewriteBase /

RewriteCond %{HTTP_HOST} ^mydomain.com$ [NC]
RewriteRule ^(.*)$ http://www.mydomain.com/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ /index.php?site=$1 [L]

What could I do to redirect only the part after the last slash?
Thank you so much!


SOLUTION:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*/)?([^/]+)$ $1index.php?site=$2 [L]

回答1:

Found this other, on my opinion more elegant solution. By this, the number of subfolders is irrelevant.


SOLUTION:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*/)?([^/]+)$ $1index.php?site=$2 [L]


回答2:

Finally figured out the answer myself.
At first I tried putting more RewriteRules under the same RewriteCond-lines gave me server errors. So I duplicated the RewriteCond-lines for the subdirectories:

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)/(.*)$ $1/index.php?site=$2 [L]

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ /index.php?site=$1 [L]