首頁  >  文章  >  後端開發  >  如何在 .htaccess 中使用 GET 變數重寫 URL 以實現乾淨路由?

如何在 .htaccess 中使用 GET 變數重寫 URL 以實現乾淨路由?

Linda Hamilton
Linda Hamilton原創
2024-11-15 11:34:03260瀏覽

How Can I Rewrite URLs with GET Variables in .htaccess for Clean Routing?

Rewriting URLs with GET Variables in .htaccess

When using PHP for routing purposes (e.g., index.php?page=controller), it is useful to have a cleaner and more user-friendly URL structure. .htaccess, a widely used Apache configuration file, provides a convenient way to rewrite URLs and handle GET variables.

In the given situation, the goal is to have URLs like http://localhost/controller/ route to index.php?page=controller in a clean and concise manner. Additionally, the requirement is to support URLs with parameters, such as http://localhost/controller/param/value/param/value, which should map to http://localhost/controller/?param=value¶m=value with the GET variables.

To achieve this, a simple yet effective solution can be implemented using a rewrite rule in the .htaccess file:

RewriteRule ^([\w\d~%.:_\-]+)/(.+)$ index.php?page=$1&params=$2 [NC, QSA]
  1. Rewrite Pattern: The RewriteRule starts with the pattern ^([\w\d~%.:_\-]+)/(.+)$, which matches any URL consisting of a controller name followed by a slash and any additional parameters separated by slashes.
  2. Target URL: The target URL is index.php?page=$1¶ms=$2. Here, $1 represents the controller name, and $2 represents the entire parameter string.
  3. Rewrite Flags: The NC flag (No Case) ensures case-insensitive matching, while the QSA flag (Query String Append) concatenates the existing GET string with the parameters from the rewrite rule.

With this rule in place, a URL like http://localhost/controller/param/value/param/value will be rewritten to index.php?page=controller¶ms=param/value/param/value. This provides a clean and easy way to manage GET parameters and maintain the original URL structure.

To access these parameters in your PHP code, you can use $_GET['params'], which contains the parameter string. You can then split it using a delimiter (e.g., /) and access individual parameter values.

以上是如何在 .htaccess 中使用 GET 變數重寫 URL 以實現乾淨路由?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn