.htaccess url rewrite querystring

岁酱吖の 提交于 2019-12-06 10:09:52

If you want to get ID, you shell do next:

  1. Enable mod_rewrite the apache module
  2. Create .htaccess in the DocumentRoot directory
  3. Paste next:

    RewriteEngine On
    RewriteRule ^([0-9]+)$ /page.php?channel=$1
    
  4. When you follow the URL:

http://www.mysite.com/1

you get content like from URL:

http://www.mysite.com/page?channel=1

There are a number of ways of doing this.

Using a MVC architecture in your application will force you to use a routing logic in one form or another.

What you specifically want can be done in a number of ways, including apache RewriteMap.

I'd personally design my application in such a way that it receives the URI's and routes them to a controller/page. This ensures that PHP continues to have full control over what is finally displayed for a request.

Assuming you are given the task of beautifying your links without affecting much of the application, you need to find a way to map /page/description to /page?channel=1.

For this unique situation, I would use something similar to a decorator pattern, because in its essence your task does not need to modify the existing codebase:

.htaccess

RewriteEngine On
RewriteRule ^.*$ router.php [NC,L]

router.php

include'config.php';// remove your config loading from index.php

$request = $_SERVER['REQUEST_URI'];
$request = explode('/', $_request);
    # in $request you will have all the uri segments now

/* complex logic to find out what page you're on */

   # assuming we found out it's page/description
$_GET['channel'] = 1;// or getIdFromDescription($request[2])
   # this forces the environment to believe it got a request with ?channel=1

# revert to your old request with injected environment
include'index.php';

The premise here is that index.php can load your old pages. And you just need to change the way they are accessed. So you use a router to map the new request to the old request.

It's not perfect, but works well on poorly designed applications.

TAKE NOTE: My current implementation does not handle static resources (images, css, js, etc)

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