dynamic URL rewriting .htaccess

房东的猫 提交于 2019-12-08 08:04:19

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/10333392/dynamic-url-rewriting-htaccess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!