2014-10-04 25 views
0

我使用.htaccess看过/读过有关干净网址的问题,但对于我的生活,我无法让他们为我的特定需求而工作。我不断收到404消息。如何仅为2个变量获取干净的URL?

例子:www.mysite.com/article.php?id=1 &标题= MY-博客标题

我想为网址是:www.mysite.com/article/1/my -blog标题

这里是我迄今为止在我的.htaccess:

Options -MultiViews 
#DirectorySlash on 
RewriteCond %{HTTP_HOST} !^www [NC] 
RewriteRule .* http://www.%{HTTP_HOST}%{REQUEST_URI} [L] 


# Rewrite for article.php?id=1&title=Title-Goes-Here 
RewriteRule ^article/([0-9]+)/([0-9a-zA-Z_-]+) article.php?id=$1&title=$2 [NC,L] 

#Rewrite for certain files with .php extension 
RewriteRule ^contact$ contact.php 
RewriteRule ^blogs$ blogs.php 
RewriteRule ^privacy-policy$ privacy-policy.php 
RewriteRule ^terms-of-service$ terms-of-service.php 

而且,这是我怎么会链接到文章? article.php?id=<?php echo $row_rsBlogs['id']; ?>&slug=<?php echo $row_rsBlogs['slug']; ?>article/<?php echo $row_rsBlogs['id']; ?>/<?php echo $row_rsBlogs['slug']; ?>

我使用Dreamweaver,但我很舒适的手工编码。

在此先感谢。

+0

之前'制品只需添加一个斜线。 php'在你的规则。有这样的方式:'RewriteRule^article /([0-9] +)/([^ /] +)$ /article.php?id=$1&title=$2 [NC,L]'。此外,这更好地改变你的第二个例子的链接(即使可以用规则重定向) – 2014-10-04 19:31:11

+1

谢谢贾斯汀!这是完美的!非常感激!我不知道我怎么能给你答案的答案。旁边没有上/下的投票。只要知道你的技巧!谢谢!!!!! – Soletwosole 2014-10-04 20:35:12

回答

2

您可以通过告诉网络服务器将所有请求重定向至的index.php .. 在有调度实例analizes请求并调用某些控制器(例如articlesControllers)

class Dispatcher 

{ 

    // dispatch request to the appropriate controllers/method 

    public static function dispatch() 

    { 

     $url = explode('/', trim($_SERVER['REQUEST_URI'], '/'), 4); 

     /* 
     * If we are using apache module 'mod_rewrite' - shifting that 'request_uri'-array would be a bad idea :3 
     */ 
     //array_shift($url); 

     // get controllers name 

     $controller = !empty($url[0]) ? $url[0] . 'Controller' : 'indexController'; 

     // get method name of controllers 

     $method = !empty($url[1]) ? $url[1] : 'index'; 

     // get argument passed in to the method 

     $parameters = array(); 

     if (!empty($url[2])) { 

      $arguments = explode('/', $url[2]); 

      foreach ($arguments as $argument) { 
       $keyValue = explode('=',$argument); 
       $parameters[$keyValue[0]] = $keyValue[1]; 
      } 

     } 


     // create controllers instance and call the specified method 

     $cont = new $controller; 
     if(!method_exists($cont,$method)) { 
      throw new MethodNotFoundException("requested method \"". $method . "\" not found in controller \"" . $controller . "\""); 
     } 
     $cont->$method($parameters); 

    } 

} 

在.htaccess


RewriteEngine On 

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^.*$ index.php 
+0

感谢您回答我的问题Erik。我不确定调度员在做什么。我将不得不阅读它。这是否解决了我的.htaccess中的所有功能?或者我需要专门为article.php编辑? #clueless – Soletwosole 2014-10-04 20:39:45

+0

它是一种替代:)而不是写你的“路线”(/ articles/1 /)到.htaccess文件中,它分析所有请求并调用相应的控制器。 – 2014-10-05 14:29:24

+0

/articles/1 - >意思是“开始articlesController.php并加载文章”1“ – 2014-10-05 14:30:21