1

I am trying to build a custom PHP MVC framework, I want to do the following using .htaccess rewrite

localhost/mvc/page1 OR localhost/mvc/page1/
To this
localhost/mvc/index/view/page1

AND

localhost/mvc/blog OR localhost/mvc/blog/
To this
localhost/mvc/blog/index

AND

localhost/mvc/blog/blog1 OR localhost/mvc/blog/blog1/
To this
localhost/mvc/blog/view/blog1

here index and blog are controllers

Below is what I have tried so far

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?rt=index/view/$1 [L,QSA] 

This redirects localhost/mvc/page1 To localhost/mvc/index/view/page1

So basically, I want to have different rewrite conditions for different controllers. So when I will add a new controller I will keep adding condition to htaccess file as well.

This is a code behind redirect (URL should not change),. and everything behind localhost/mvc/ should be reflected in GET $_GET['rt'] parameter

How to achieve this??

1 Answer 1

2

Have it this way:

RewriteEngine on
RewriteBase /mvc/

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteRule ^(blog)/?$ index.php?rt=$1/index [L,NC,QSA] 

RewriteRule ^(blog)/([^/]+)/?$ index.php?rt=$1/view/$2 [L,NC,QSA] 

RewriteRule ^(.+)$ index.php?rt=index/view/$1 [L,QSA]
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks so much.. that worked :).. so whenever I want to add a new controller, I have to add the redirect rule before that default index rule right??
Yes that's right, last rule is catch-all controller.
Just for curiosity .. How to redirect if I have something like localhost/mvc/blog/blog1/edit to localhost/mvc/blog/view/blog1/edit
Then change 2nd rule to RewriteRule ^(blog)/(.+)/?$ index.php?rt=$1/view/$2 [L,NC,QSA]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.