2014-10-04 99 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