dynamic URL rewriting .htaccess

2019-06-06 08:38发布

I'm new to URlRewriting and I've been having some problems rewriting my URLs, I have one single .php index page in which the content is filled using php depending on the url variables.

My problem is that I cannot seem to find the correct expressions to get it working. For my homepage I'm only sending out 1 variable like

"index.php?page=home"

BUT for other pages I'm using up to 4 variables like "index.php?page=about&content=about-news&id=27&pn=1"

Now I got as far as getting 1 or 2 working seperately but not together using:

RewriteRule ^((.*)+)$ index.php?page=$1

OR

RewriteRule ^(.*)/(.*)$ index.php?page=$1&content=$2

I've been looking around on google and Stackoverflow for the past few days but I cannot seem to find a working solution, does anyone have any ideas of how to get this working? Cheers

2条回答
不美不萌又怎样
2楼-- · 2019-06-06 09:01

Try:

#Make sure it's not an actual file
RewriteCond %{REQUEST_FILENAME} !-f 

#Make sure its not a directory
RewriteCond %{REQUEST_FILENAME} !-d 

#Rewrite the request to index.php
RewriteRule ^(.*)$ index.php?/$1 [L]

You can then look at the $_SERVER['REQUEST_URI'] variable to see what was asked for.

That should work for you, let me know how you get on.

查看更多
▲ chillily
3楼-- · 2019-06-06 09:19

All you need is one rewrite:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]

then in your index.php file your split the route into piecies:

$route = (!isset($_GET['route']))?'':$_GET['route']);
$parts = explode('/', $route);

So your old urls like this:
index.php?page=home 
index.php?page=about&content=about-news&id=27&pn=1
index.php?page=$1
index.php?page=$1&content=$2

Become:
Example: `http://example.com/controller/action/do/value`
or       `http://example.com/$parts[0]/$parts[1]/$parts[2]/$parts[3]/$parts[4]`

Keeping to the idea of controller->action->do->value its easy to assign routes.

?page= will be your controller

?content= will be your action

?id= will be your subaction | do | value ect

查看更多
登录 后发表回答