Need help to replicate .htaccess mod_rewrite redirection function in php like Wordpress
We all know that wordpress have simple .htaccess code like below RewriteEngine on RewriteBase /
# only rewrite if the requested file doesn't exist
RewriteCond %{REQUEST_FILENAME} !-s
# pass the rest of the request into index.php to handle
RewriteRule ^(.*)$ /index.php/$1 [L]
But if I redirect all requests to index.php, I think it becomes pretty cumbersome to handle every rewrite in php. Currently I have a logic in mind, like maintain a db table with all valid redirections. But still I don't know how to handle rules likes ([0-9]+).
If anyone has implemented something like this before or has a logic in mind, can you please guide me in this matter
The sole purpose am doing this, is because I want flexibility in add开发者_运维知识库ing/deleting categories in the menu of my site. I don't want to go to .htaccess every time and edit it at all places. I want to create more like a CMS where user can add delete categories
My suggestion would be to set up php based routing the basic idea is that you do something like this:
RewriteEngine On
# skip all files with extensions other than .html
# this way if you want you can append the .html to dynamic pages
# which wont really exist as a file
RewriteCond %{REQUEST_URI} \..+$
RewriteCond %{REQUEST_URI} !\.html$
RewriteRule .* - [L]
// redirect everything to your front controller
RewriteRule ^(.*)$ index.php [QSA,L]
Notice how you just make everythign go to index.php
but you dont rewrite any of the variables or anything. This is because you will work out what to based on the pattern of the URL with php. In order to do this youll need to implement a router. Basically a router takes a request and matches it against a pattern and then determines any parameters based on the pattern.
There are existing libraries out there to do this for you. For example Zend_Controller_Router
.
I don't understand the question, WordPress already handles all this for you. Unless you mean you aren't using WordPress? In which case yes, you can do it either way. What kind of URL structure do you want? You could write a rule like so:
RewriteRule ^category/(.*)$ categories.php?cat=$1 [L]
To make a URL like domain.com/category/dogs rewrite to domain.com/categories.php?cat=dogs. Obviously you can adjust this to your liking, and write a few more similar rules for tags, posts etc.
Handling routing in php would be a more dynamic and 'elegant' solution. You could try using a framework like CodeIgniter, this will manage routes for you automatically and make it easy to define custom routes. Probably better than writing a bunch of .htaccess rules.
精彩评论